0

I am using Math.round(). This is the sample code:

double value = 0.14499999970197677;

value = 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.13499999970197677, then it is returning 0.13, why not 0.14

I have already gone through the link round up to 2 decimal places in java?

Please tell me clearly that why this is happening with both the numbers?

Akanksha
  • 29
  • 2
  • `0.14499999970197677 * 100` == `14.499999970197677`. `Math.round(14.499999970197677)` == `14`. `14/100` == `0.14`. Do you rather want to ceil it? – ernest_k Jun 24 '19 at 06:21
  • 1
    "My expectation is it should return 0.15" - could you explain *why* you have that expectation? – Jon Skeet Jun 24 '19 at 06:27
  • If you want to apply the mathematical principles behind rounding a value, then you should - assume that you want to have a precision of two decimals - expect `0.14` and not `0.15`. Assume that the aim is a three decimal precision, then you get `0.145`. So I don't understand why you want `0.15`. Maybe you made a small mistake in your expectations? – KarelG Jun 24 '19 at 06:30
  • Tip: If you want accurate fractional numbers, and flexible rounding, use `BigDecimal`. – Basil Bourque Jun 24 '19 at 06:42
  • If you've already been through that link you should already have learned that your expectations are not correct. – user207421 Jun 24 '19 at 08:02

1 Answers1

-1

In Java, Math.round rounds up/down to closest long value (in mathematics terms, closest whole number).

14.49 will be rounded to 14 (because it is treated as 14.4). It won't take the .09 into account.

Edward Aung
  • 3,014
  • 1
  • 12
  • 15
  • Can someone care to explain why the down-vote ? It directly answers the question (even if it may not be the best quality answer). – Edward Aung Jun 25 '19 at 01:31