Formatting a double and not rounding off
35,987
Solution 1
Call setRoundingMode
to set the RoundingMode
appropriately:
String s1 = "10.126";
Double f1 = Double.parseDouble(s1);
DecimalFormat df = new DecimalFormat(".00");
df.setRoundingMode(RoundingMode.DOWN); // Note this extra step
System.out.println(df.format(f1));
Output
10.12
Solution 2
You can set the rounding mode of the formatter to DOWN:
df.setRoundingMode(RoundingMode.DOWN);
Solution 3
Why not use BigDecimal
BigDecimal a = new BigDecimal("10.126");
BigDecimal floored = a.setScale(2, BigDecimal.ROUND_DOWN); // == 10.12
Author by
SMA_JAVA
Updated on July 14, 2020Comments
-
SMA_JAVA almost 4 years
I need to format (and not round off) a
double
to 2 decimal places.I tried with:
String s1 = "10.126"; Double f1 = Double.parseDouble(s1); DecimalFormat df = new DecimalFormat(".00"); System.out.println("f1"+df.format(f1));
Result:
10.13
But I require the output to be
10.12
-
SMA_JAVA over 12 yearsYou mean Math.round(arg0); ?? Actually that would round it off to the closest integer.
-
John B over 12 yearsNo DecimalFormat's setRoundingMode
-
SMA_JAVA over 12 yearsThanks for the suggestion..but i need to use java 1.5 ..i guess the setRoundingMode() is available in 1.6
-
SMA_JAVA over 12 yearsThanks man....i can use it ...but then i wanted something more compact..and also i need to do a couple of calculations on these values, so any ways there will be some amount of parsing required
-
Brad over 12 yearsSee my answer using BigDecimal instead
-
Bohemian over 12 yearsYes, I am using the current version - 1.6. It would behoove you to upgrade your version too.