KaliMa KaliMa - 8 months ago 68
Java Question

Java formatting decimals to 2 digits precision

Right now I am doing this

DecimalFormat df = new DecimalFormat("#.##");
//usage: df.format(someDouble);

But I don't know if this is the correct way to "round off" the display of a double to 2 decimal points. Will this work even if the number of digits to the left of the decimal point > 1?

Answer Source

You should use:

DecimalFormat df = new DecimalFormat("#.00");

DecimalFormat df = new DecimalFormat("#.##"); means, that those decimal places are optional. You can see the difference when applying on 1.2 or 1.0.

enter image description here