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
Share:
35,987
SMA_JAVA
Author by

SMA_JAVA

Updated on July 14, 2020

Comments

  • SMA_JAVA
    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
    SMA_JAVA over 12 years
    You mean Math.round(arg0); ?? Actually that would round it off to the closest integer.
  • John B
    John B over 12 years
    No DecimalFormat's setRoundingMode
  • SMA_JAVA
    SMA_JAVA over 12 years
    Thanks for the suggestion..but i need to use java 1.5 ..i guess the setRoundingMode() is available in 1.6
  • SMA_JAVA
    SMA_JAVA over 12 years
    Thanks 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
    Brad over 12 years
    See my answer using BigDecimal instead
  • Bohemian
    Bohemian over 12 years
    Yes, I am using the current version - 1.6. It would behoove you to upgrade your version too.