Android number format is wrong somehow, instead of

2020-04-16 04:31发布

问题:

I store some data in a database and I read those data with a cursor. All the data are 56.45 , 3.04, 0.03 type, so two numbers after the decimal point. Now I would like to sum them but it doesnt seem to be easy... I get those number with c.getDouble(3) then I add it to the sum variable like:

sum+= c.getDouble(4) * multi

multi is an integer between 1 and 100. Now my problem is that, after getting the sum variable I get a number like: 59.51999999999999999. I do not post a code, but there is no conversion except a string.valueOf for making the number appear on my widget. So anybody experienced this? As I count it should be 59.52, but instead I get that number with 99999... Why is that happening? (funny thing that with a Math.round() does not work, I get 59.0 even if I set (sum)*100 / 100.. Thanks in advance!

回答1:

Other approach, you can define your sum variable as double and then you can set NumberFormat for your sum variable.

Example:

double sum = 21.2015;
NumberFormat formatter = new DecimalFormat("#.##");
formatter.format(sum);


回答2:

Your numbers are represented in decimal to you, but binary to a computer.

In both decimal and binary, some fractions cannot be represented precisely.

For example 1/3 cannot be represented precisely in decimal. You can merely approximate it with something like 0.3333333333. But then if you try to do 3 * 0.3333333333, you end up with 0.9999999999 instead of 1.0000000000.

In binary, you have the same problem, but with different fractions.

So, sometimes when you convert from decimal to binary and back again (which is what the computer basically must do to do floating point arithmetic for you), you get small errors in precision even though all the numbers are perfectly precise in decimal. When the computer uses their binary near-equivalents, approximations are introduced and they result in small errors.

This is actually a very common issue in programming. For a lot more detail, see What Every Computer Scientist Should Know About Floating-Point Arithmetic.