posted 4 years ago

I have a issue in java rounding

when we are rounding 63.825 to two decimal, what is the answer??

63.82 OR 63.83

Answer :

63.825

98.975

NumberFormat

63.82

98.98

printf

63.83

98.98

DecimalFormat

63.82

98.98

Math.round

63.83

98.98

when we are rounding 63.825 to two decimal, what is the answer??

63.82 OR 63.83

Answer :

63.825

98.975

NumberFormat

63.82

98.98

printf

63.83

98.98

DecimalFormat

63.82

98.98

Math.round

63.83

98.98

Varun Selva

Campbell Ritchie

Marshal

Posts: 56599

172

posted 4 years ago

- 1

Mathematically, I would use half‑away‑from‑zero rounding, and get 63.83, 98.98. You will have to look through the API to see what type of rounding those three methods use. I also suggest you print out a BigDecimal…so you can see how close to 8.25 you are actually getting. You cannot represent 0.825 exactly in binary.

I shall move this discussion as not geing a beginner's topic.

I shall move this discussion as not geing a beginner's topic.

posted 4 years ago

Hi Campbell Ritchie,

Thanks for your response.

result for above code is (new java.math.BigDecimal(63.825))

63.8250000000000028421709430404007434844970703125

98.974999999999994315658113919198513031005859375

How is it coming?

anyway, result should be mathematical answer.. is it???

Thanks for your response.

result for above code is (new java.math.BigDecimal(63.825))

63.8250000000000028421709430404007434844970703125

98.974999999999994315658113919198513031005859375

How is it coming?

anyway, result should be mathematical answer.. is it???

Varun Selva

posted 4 years ago

NumberFormat lets you set the rounding mode from the choices in java.math.RoundingMode. The default throughout the Java platform, as far as I know, is half-even rounding. That means 63.825 to two decimal places is 63.82, but 63.855 would be 63.86. That is, if the part you want to round is exactly halfway between the upper bound and lower bounds, then you round in the direction of the even digit. It's meant to prevent introducing cumulative errors in long calculations.

Of course, by that rule, 63.8250000000000028421709430404007434844970703125 should round to 63.83. It seems Java is treating that as exactly 63.825 though. I'm not sure how that works.

Of course, by that rule, 63.8250000000000028421709430404007434844970703125 should round to 63.83. It seems Java is treating that as exactly 63.825 though. I'm not sure how that works.