简体   繁体   中英

How to check if a Double has java rounding?

Is there anyway to check if a Double has java rounding eg -260.01079999999996

I have one system that passes a computed Double value. By right should be -260.0108.

When using floats and doubles, the "issues" with rounding are due to the limitations of digital computers.

If you don't want rounding, use integers. If you need to save a number with a fixed number of digits after comma, use a BigDecimal ; or always round your double at Xth digit after comma; or use the number as integer while dividing or multiplying it by 10^n before showing in view (elaboration below).

For example, you could save -2600108 as integer and a factor 1000 . Addition, subtraction, multiplication and saving work flawlessly and without side-effects in this case. Division needs doubles though.

If you know from external evidence that the exact answer at a certain point in your code must be an integer, round to nearest integer there.

Otherwise, you get the most accurate double result by carrying the full precision through your calculations, using DecimalFormat to print only the meaningful digits.

There is nothing special about "java rounding". The special thing is that the default output preserves enough digits to uniquely identify the double. Many other languages, by default, round to fewer digits, losing accuracy but making results look tidier.

Using BigDecimal is a major win if every number in the calculation can be exactly represented as a short decimal fraction. That often happens for currency calculations. However, as soon as you hit a fraction such as 1/3 that cannot be exactly represented by any finite number of decimal digits, you have to deal with rounding error anyway. For many financial calculations, there are fixed rules for rounding.

In theory, BigDecimal could also be used to get extra precision, but that is rarely practical.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM