Android开发 - SQLite的存储浮动 [英] Android development - SQLite storing float

查看:92
本文介绍了Android开发 - SQLite的存储浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我店浮点值WIDT SQLiteDatabase.insert存储的值会比原来的不同,见下图:

When I store float value widt SQLiteDatabase.insert the stored value will be different than the original, see below:

我有一个数据库宽度:

db.execSQL("CREATE TABLE IF NOT EXISTS info_values ("
    + BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + "date DATE UNIQUE NOT NULL, "
    + "value REAL NOT NULL)");

当我插入如33.3宽:

When I insert eg 33.3 width:

private class inputdlg_ok implements input_dlg.ReadyListener {
    public void ready(float newvalue) {
      Date d = new Date();
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
      ContentValues values = new ContentValues();
      values.put("date", sdf.format(d));
      values.put("value", newvalue);

      database.insert("info_values", null, values);

我有这些:

sqlite> select * from info_values;
83|2012-04-04 09:06:22|33.2999992370605
84|2012-04-02 09:05:57|22.2000007629395

我已经测试宽度EXEC:

I have tested width exec:

 String sql = "INSERT INTO info_values (date, value) " + 
              "VALUES ('" + sdf.format(d) + "'," + Float.toString(newvalue) + ")";
database.execSQL(sql);

和形式的作品不错。

and that form works good.

任何想法?

推荐答案

从来没有想过这个线程可以帮助其他人,但在这里它allas 那张的。

Never thought this thread will help anybody else, but allas here it goes.

基本上你的问题是,你使用浮动在Java的code类型。浮动是非常低的precision。读线程我链接到,所有的意见和链接的聊天。如果您还有任何问题,写回。

Basically your problem is that you use float for the type in the java code. Float is with very low precision. Read the thread I link to, together with all comments and the linked chat. If you still have any problems write back.

您可能知道,双值存储高达只在电脑一定precision。即使值数据库看起来很怪异,这是你的价值观,你可以使用浮动时,你得到的最好的逼近。采用双可以增加precision,但你永远不会得到完美的状态。也许,如果你坚持要precise值限制在数据库中的实际规模可能是很长的路要走。

You probably know that the double values are stored only upto certain precision in the computers. Even though the values look weird in the database, this is the best approximation of your values you can get when using float. With double you can increase the precision, but you will never get to perfect state. Maybe if you insist on getting precise values limiting the real size in the database might be a way to go.

修改,因为我无法让你相信这是一个precision问题,我有以下程序:

EDIT As I could not make you believe it IS a precision problem I include the following program:

float f = 22.2;
printf("The number is: %.9f\n", f);

输出是:

22.200000763

我建议你试试吧。正如你所看到的,这正是你所指出的数量。

I suggest you try it. As you can see this is exactly the number you point out.

这篇关于Android开发 - SQLite的存储浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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