-4

I am trying to convert a string to double using Double.valueOf(String s) function and multiply it by 100. The result works fine for most of the numbers except for some. For example, if the amount is 10.20 and i use Double.valueOf(10.20) * 100, the result is 1019.9999 instead of 1020.0. This only happens for 10.20, 8.20, 9.20. It works fine for 7.20, 1.20, 11.20 etc. What is the reason for this? Below is the snippet of my code

1st scenario

String s = "10.20"; *System.out.println("the value after double manipualtion is" +(Double.valueOf(firstHalf) 100 ));

Result :- the value after double manipualtion is1019.9999999999999

Where as the actual result should be 1020.0. If i give the following, it works fine

2nd Scenario

*String s = "7.20"; System.out.println("the value after double manipualtion is" +(Double.valueOf(firstHalf) 100 ));

Result:- the value after double manipualtion is720.0

Any help would be appreciated

  • It's not "bad". Just format the number appropriately (i.e. with limited decimal precision of say, 0) and it should "look ok" again. Anyway, see [What Every Computer Scientist Should Know About Floating-Point](https://ece.uwaterloo.ca/~dwharder/NumericalAnalysis/02Numerics/Double/paper.pdf) – user2246674 Sep 03 '13 at 23:28

2 Answers2

0

Use BigDecimal

BigDecimal newValue = BigDecimal.valueOf(10.20)
   .setScale(2, RoundingMode.HALF_UP)
   .multiply(BigDecimal.valueOf(100));
Alex
  • 11,451
  • 6
  • 37
  • 52
0

You get bad results because Java uses binary floating point standard to represent floating point numbers. Not every decimal number can be represented as a binary fraction. You must use java.math.BigDecimal
Already explained here: Floating point arithmetic not producing exact results

Make sure to use BigDecimal(String) constructor for floating point numbers, avoid BigDecimal(double) constructor:
new BigDecimal("10.20").multiply(new BigDecimal(100)).toString()

Community
  • 1
  • 1
Sergej Panic
  • 854
  • 5
  • 8