dtrembl5 dtrembl5 - 1 month ago 11
Java Question

Java convert a format.String

I'm still new to Java and is there are any ways to make sure a decimal number doesn't get rounded at two decimals when formatting a double.
Exemple:

double n = 0.12876543;
String s = String.format("%1$1.2f", n);


if I were to do a print to the system, it would return the 0.13 instead of the precise 0.12. Now I have thought of a solution but I want to know if there is a better way of doing this. This my simple solution:

double n = 0.12876543;
double n = Double.parseDouble(String.format(("%1$1.2f", n));


Any other thoughts or solutions?

Answer

An elegant solution would be to use setRoundingMode with DecimalFormat. It sets the RoundingMode appropriately.

For example:

// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Print statement
System.out.println(curDf.format(n));

Output:

0.12

Further, if you want to do additional formatting as a string you can always change the double value into string:

// Your decimal value
double n = 0.12876543;
// Decimal Formatting
DecimalFormat curDf = new DecimalFormat(".00");
// This will set the RoundingMode
curDf.setRoundingMode(RoundingMode.DOWN);
// Convert to string for any additional formatting
String curString = String.valueOf(curDf.format(n));
// Print statement
System.out.println(curString);

Output:

0.12

Please refer similar solution here: http://stackoverflow.com/a/8560708/4085019