Android的数字格式不对不知何故,而不是3.5我得到3.499999999,为什么呢?何故、什么呢、而不是、格式

2023-09-07 15:56:53 作者:陌路〃荒年

余存储在数据库中的一些数据,并予读与游标那些数据。所有的数据是56.45,3.04,0.03的类型,所以小数点后两个数字。现在,我想总结他们,但它似乎不容易......我得到这些数字与 c.getDouble(3)然后我把它添加到喜欢的总和变量

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

多为1到100之间的整数,现在我的问题是,得到的总和变量后,我得到了一些像:59.51999999999999999。我不发表code,但有除外将String.valueOf 制作的数量出现在我的窗口小部件没有任何转换。所以任何经验?正如我算它应该是59.52,而是我得到这个数字与99999 ......这是为什么发生? (有趣的事情,与一个 Math.round()不工作,我得到59.0即使我设定(和)*百分之百.. 在此先感谢!

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!

推荐答案

其他的方法,你可以定义你的总和变量,然后你可以设置的NumberFormat 为您的总和变量。

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

示例:

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