Search code examples
javafloating-pointdouble

How to REDUCE decimal values from a value of type 'double' in Java


This is probably a really simple question but, is there a simple way to go from

Double myLongNumber = 50.12345678998658576546

to

Double myLongNumber = 50.1234

?

I just want to reduce the number of decimal digits, not remove them all.


Solution

  • If you really want to change that number, you can do something like

    Double myNotSoLongNumber = Math.round(myLongNumber * 1E4) / 1E4;
    

    If you want to display a Double with less fraction digits, use

    String myLongNumberAsString = String.format("%.4f", myLongNumber);