-2

I want to convert String "0.955000" to "0.96" using Java DecimalFormat

Here's my code snippet:

String inputVal = "0.955000";
DecimalFormat decFmt = new DecimalFormat("0.00")
decFmt.setRoundingMode(RoundingMode.HALF_UP);
String outputVal = decFmt.format(Double.valueof(inputVal));

Here I get the output value as "0.95". I was expecting output to be "0.96". Does anyone know what's wrong in my code? And is there a way, I can get "0.96" using decimal format.

Mel
  • 5,837
  • 10
  • 37
  • 42
  • 8
    Your title talk about an issue with `BigDecimal`, but your code doesn't use it. With what do you need help? – Tunaki Jun 24 '16 at 20:21
  • 1
    To tack onto @Tunaki 's answer, if you were using BigDecimal, you could use the `.setScale(..)` method and accomplish what you want. – lucasvw Jun 24 '16 at 20:22
  • 1
    Ahem, `double` precision. – Boris the Spider Jun 24 '16 at 20:22
  • Why using `DecimalFormat` to perform the rounding which `BigDecimal` supports this directly. If you want to do your own rounding you may as well use `double`. – Peter Lawrey Jun 24 '16 at 20:39
  • 1
    Possible duplicate of [RoundingMode.HALF\_DOWN issue in Java8](http://stackoverflow.com/questions/30778927/roundingmode-half-down-issue-in-java8) – Xiong Chiamiov Jun 24 '16 at 21:51

2 Answers2

2

This is the code I tried:

import java.math.RoundingMode;
import java.text.DecimalFormat;


public class Test
{
  public static void main(String[] args)
  {
    String inputVal      = "0.955000";
    DecimalFormat decFmt = new DecimalFormat("0.00");
    decFmt.setRoundingMode(RoundingMode.HALF_UP);
    String outputVal = decFmt.format(Double.valueOf(inputVal));
    System.out.println(outputVal);
  }
}

The output I got using jdk 7 is 0.96 but with jdk 8 I got 0.95.

Here is why: 0.955 as double is: 0.9549999833106995 in IEEE binary format

The round half up will become: 0.95 which is the correct answer.

Wael
  • 1,533
  • 4
  • 20
  • 35
0

Found the issue with this. Earlier I was trying with Java 7 and was getting 0.96. Now after changing to Java 8, I got it as 0.95. I thinks it's a Java version issue. Java 7 and 8 are behaving differently for Decimal Format.

  • The correct output is 0.95 and not 0.96 this is because the double is stored in IEEE binary format. See my update above – Wael Jun 24 '16 at 21:08