SQLite的如何使用整型来存储价格值 [英] SQLite how to use integer for storing price value

查看:160
本文介绍了SQLite的如何使用整型来存储价格值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的实型保存在SQLite数据库价值,但它不返回正确值。如果我像保存几个值1.01 将返回 4.029999999999999
我已阅读保存价格的SQLite是最好的方法是使用整数<一个href=\"http://dba.stackexchange.com/questions/15729/storing-prices-in-sqlite-what-data-type-to-use\">type

但我不知道如何使用它。
如何存储和在这种情况下,检索的价格?
在这里,code我现在该怎么找回价:

 光标指针= NULL;
    双totalPrice = 0;
    尝试{
        光标= mDB.rawQuery(从+ Expense.TABLE_NAME +,其中+选择+ Expense.PRICE +(的strftime(
                + dateType +,+ Expense.DATE +))+=?,新的String [] {的currentdate});    }赶上(例外五){
        Log.e(TAG,错误+ e.toString());
        e.printStackTrace();
    }
    为(cursor.moveToFirst();!cursor.isAfterLast(); cursor.moveToNext()){
        totalPrice + = cursor.getDouble(cursor.getColumnIndex(Expense.PRICE));
    }


解决方案

当你看到它其实原因很简单。

我不知道你在什么货币,但美国承担$。

您想存储$ 1.01这是相同的101美分。你只需乘以100。

所以存放在号码前,乘以100。
当显示的数目,除以100


只是要添加到答案:我也想你应该存储的数字在内存中美分/整数了。因此,对于所有的工作原理,计算等,使用该整数格式。

如果用户输入$量,将其转换直线距离为整数(乘以100)。而且,只有当你需要显示它改回$。

在换句话说,将要与从数据库中不只是当

I am using real type to save price value in SQLite database but it does not return correctly value. If I save a few values like 1.01 it will return 4.029999999999999. I have read that best way to save prices in SQLite is to use integer type

But I don't know how to use it. How to store and retrieve prices in this case? Here code how I retrieve price now:

        Cursor cursor = null;
    double totalPrice = 0;
    try {
        cursor = mDB.rawQuery("select " + Expense.PRICE + " from " + Expense.TABLE_NAME + " where " + " (strftime("
                + dateType + ", " + Expense.DATE + "))" + "= ? ", new String[] { currentDate });

    } catch (Exception e) {
        Log.e(TAG, "error" + e.toString());
        e.printStackTrace();
    }
    for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
        totalPrice += cursor.getDouble(cursor.getColumnIndex(Expense.PRICE));
    }

解决方案

It is actually quite simple when you see it.

I don't know what currency you are in, but assume US $.

You want to store $1.01. This is the same as 101 cents. You just multiply by 100.

So before storing the number, multiply by 100. When displaying the number, divide by 100.


Just to add to that answer: I also think you should store the numbers in memory as cents/integers too. So for all your workings, calculations etc, use that integer format.

If a user enters a $ amount, convert it straight away into integer (multiply by 100). And only change back to $ when you need to display it.

In other words, not just when going to and from the database.

这篇关于SQLite的如何使用整型来存储价格值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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