Frank Jacobsen

Ranch Hand

Posts: 358

posted 10 years ago

Keep in mind though that the double will become incorrect again if you do a lot of math with it. For example:

Output:

4.85999999999

486

4.86

4.86000000000001

This is caused because just like humans cannot write 1/3 without rounding at some point, PCs cannot write most decimal numbers (including 1/10) without rounding. That's because PCs use only factors of 2: ..., 32, 16, 8, 4, 2, 1, 1/2, 1/4, 1/8, ...

All numbers are constructed by adding these numbers, but at some point 1/10 will have to be rounded.

If you really want exact calculations with decimal numbers, either upgrade to ints / longs by multiplying with a fixed factor (e.g. with currencies use long cents instead of double dollars), or look at java.math.BigDecimal.

Keep in mind though that the double will become incorrect again if you do a lot of math with it. For example:

Output:

4.85999999999

486

4.86

4.86000000000001

This is caused because just like humans cannot write 1/3 without rounding at some point, PCs cannot write most decimal numbers (including 1/10) without rounding. That's because PCs use only factors of 2: ..., 32, 16, 8, 4, 2, 1, 1/2, 1/4, 1/8, ...

All numbers are constructed by adding these numbers, but at some point 1/10 will have to be rounded.

If you really want exact calculations with decimal numbers, either upgrade to ints / longs by multiplying with a fixed factor (e.g. with currencies use long cents instead of double dollars), or look at java.math.BigDecimal.

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6

How To Ask Questions How To Answer Questions

bart zagers

Ranch Hand

Posts: 234

posted 10 years ago

Do you want to round the number, or do you want to display/print the number rounded? If you want the latter, take a look at the DecimalFormat class.