在android系统数据库中存储浮点数 [英] Storing floating point numbers in android database

查看:135
本文介绍了在android系统数据库中存储浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图来存储货币金额由Android提供的SQLite数据库,但它似乎并没有正常工作。只有当我尝试删除不属于整个美元金额的事务会出现此错误。即409.00将工作,但410.44则不会。

如果我存储为410.44这样的值,然后查询该金额的数据库中,我没有得到匹配。我试图用这个字段作为真正的数据类型和text数据但既不工程。在下面的例子中getTransAmount()方法返回一个浮点数。这是当我有DB数据类型为REAL我跑的版本。任何帮助将是AP preciated。谢谢。

  cv.put(transAmount,t.getTransAmount());db.insert(tableName值,空,CV);
X = db.delete(tableName值,transAmount +=+ t.getTransAmount(),空);


解决方案

不要使用浮点数来存储货币金额浮点是不准确的。因为你已经发现了,浮点比较特别棘手的处理。

我通常储存货币在数据库中为整数,如达 410.44 将被存储为 41044 409.00 40900

当你需要转换为 410.44 的显示格式,您可以使用的BigDecimal 类,它传递规模,(在这种情况下,2)使用的是通过到小数点移位的位数。

例如:

  INT storedAmount = 41044;
BigDecimal的scaledAmount =新的BigDecimal(storedAmount);
scaledAmount.setScale(2); //现在包含410.44

I'm trying to store dollar amounts in the sqlite database provided by android but it doesn't seem to work properly. This error only occurs when I try to remove a transaction that aren't whole dollar amounts. i.e. 409.00 will work but 410.44 won't.

If I store a value such as 410.44 and then query the database for that amount I don't get a match. I've tried to use this field as the REAL datatype and the TEXT datatype but neither works. In the following example the getTransAmount() method returns a float. This is the version i ran when I had the db datatype as REAL. Any help would be appreciated. Thanks.

cv.put(transAmount, t.getTransAmount());

db.insert(tableName, null, cv);
x = db.delete(tableName, transAmount + " = " + t.getTransAmount(), null); 

解决方案

Don't use floating-point to store currency amounts. Floating-point is inaccurate; as you have found out, floating-point comparisons are especially tricky to deal with.

I normally store currency amounts in the database as integers, e.g. 410.44 would be stored as 41044, and 409.00 as 40900.

When you need to convert to the 410.44 format for display, you can use the BigDecimal class, passing it the scale to use (2 in this case) which is the number of digits to shift the decimal point by.

Example:

int        storedAmount = 41044;
BigDecimal scaledAmount = new BigDecimal(storedAmount);
scaledAmount.setScale(2);  // now contains 410.44

这篇关于在android系统数据库中存储浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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