1

I am using math.round() to round off.

this is the code:

double value=0.145
Math.round( value* 100.0) / 100.0; 

My expectation is it should return 0.15 but it is returning 0.14.

Also, if the value is 0.055, then it is returning 0.05 instead of 0.06 I have already gone through the link round up to 2 decimal places in java? Please tell me specific that why this is happening?

Thanks in Advance.

Akash Shah
  • 536
  • 3
  • 15
Akanksha
  • 29
  • 2
  • 1
    [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) and [Is Floating Point Broken?](https://stackoverflow.com/q/588004/18157) – Jim Garrison Jun 21 '19 at 06:49
  • 3
    Check out what `value*100` is before rounding: http://ideone.com/oNJ9h9 – Andy Turner Jun 21 '19 at 06:49

2 Answers2

0

If you would print value * 100.0, you would find that this is not actually 14.5 as you would expect, but it's close to 14.499999999999998 (on my jdk1.8.0_181). As you can see, it would give you 0.14 as final result.

Why it happened, this is how floating point arithmetic is supposed to work. When you have a value that cannot be properly represented by binary system, you will face this problem. I am giving links to answers that gives good information why it happens.

https://stackoverflow.com/a/1089026/841221

https://stackoverflow.com/a/8604224/841221

EDIT : Update 1 As matt suggested, it's actually 0.145 which cannot be represented by binary properly. As per IEEE754 Double Precision 64-Bit representation, it's actually is 1.44999999999999990007992778374E-1 which is not exactly 0.145.

Aakash
  • 1,875
  • 13
  • 22
  • 1
    In case it isn't clear, 14.5 can be exactly represented, but 0.145 cannot. So the first `value` is less than 0.145. – matt Jun 21 '19 at 07:29
  • Thank you for pointing that out @matt. I have updated my answer. – Aakash Jun 21 '19 at 07:50
0

You may use Math.ceil(0.145) to get your desired result 0.15.

Tayyab Razaq
  • 290
  • 2
  • 8