Android 数字格式在某种程度上是错误的,而不是 3.5 我得到 3.499999999,为什么? [英] Android number format is wrong somehow, instead of 3.5 I get 3.499999999, why?

查看:29
本文介绍了Android 数字格式在某种程度上是错误的,而不是 3.5 我得到 3.499999999,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将一些数据存储在数据库中,并使用游标读取这些数据.所有数据均为 56.45 , 3.04, 0.03 类型,所以小数点后有两位数.现在我想对它们求和,但这似乎并不容易......我用 c.getDouble(3) 得到这些数字,然后我将它添加到 sum 变量中,例如:

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 是 1 到 100 之间的整数.现在我的问题是,在得到 sum 变量后,我得到一个数字,例如:59.51999999999999999.我没有发布代码,但除了 string.valueOf 用于使数字出现在我的小部件上之外,没有任何转换.所以有人经历过吗?据我计算,它应该是 59.52,但我得到的数字是 99999……为什么会这样?(有趣的是,使用 Math.round() 不起作用,即使我设置 (sum)*100/100 ,我也会得到 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!

推荐答案

其他方法,你可以定义你的 sum 变量为 double 然后你可以为你的设置 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);

这篇关于Android 数字格式在某种程度上是错误的,而不是 3.5 我得到 3.499999999,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆