Android 在 SQLite 中存储双精度值:如何确保精度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3083796/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:38:20  来源:igfitidea点击:

storing double values in SQLite: how to ensure precision?

androiddatabasesqlitedoubleprecision

提问by xenonite

i have a problem with double values i need to store in an android homed sqlite database. since these double values represent gps values (lat & lng), i really NEEDan absolute precision down to the 9th number after the comma.

我有一个双值问题,我需要将其存储在 android 主控 sqlite 数据库中。由于这些双NEED精度值代表 gps 值(lat & lng),我真的是一个绝对精度,精确到逗号后的第 9 个数字。

now i have a table like this:

现在我有一张这样的表:

CREATE TABLE x REAL lng;

and insert sth (hardcoded) like:

并插入某事(硬编码),如:

INSERT INTO x lng = '1.0';

and when reading lng from this table into some (java) double variable, i get a value like "0.999956837" - this renders the values pretty useless to me.

当从这个表中读取 lng 到一些(java)双变量时,我得到一个像“0.999956837”这样的值——这使得这些值对我来说毫无用处。

is there a way to enforce the precision i need other than storing the values as "text" fields (what would make expensive casts neccessary) or storing them as integers (meaning i need to multiply/divide at each write/read-op)?

除了将值存储为“文本”字段(什么会使昂贵的转换成为必需)或将它们存储为整数(意味着我需要在每次写入/读取操作时进行乘法/除法)之外,有没有办法强制执行我需要的精度?

回答by Pentium10

SQLite is typeless, that means all representation is written as text, probably the wrapper api does some converts you don't know of, that you get those results.

SQLite 是无类型的,这意味着所有表示都写为文本,可能包装器 api 做了一些你不知道的转换,你会得到这些结果。

If you need to store the data as string do it.

如果您需要将数据存储为字符串,请执行此操作。

Just when you read out the double make sure you saved in the right format, you can use getDoubleon the column.

就当你读出双份时,确保你以正确的格式保存,你可以getDouble在列上使用。

回答by Michael Borgwardt

doublehas about 17 decimal digits of precision, so if 9 digits is what you need, there should be no problem (assuming that you don't do any complex calculations on those values). Just make sure you never end up using float, because that has only about 7 digits of precision.

double具有大约 17 位十进制数字的精度,因此如果您需要 9 位数字,则应该没有问题(假设您不对这些值进行任何复杂的计算)。只要确保你永远不会使用float,因为它只有大约 7 位的精度。

You should also make sure you understand how binary floating-point works, and that it will alwaysresult in seemingly "round" values becoming slightly off - which simply does not matter for most applications (including yours) as long as it happes somewhere in the 17th decimal digit. See that link also for alternatives for applications where it does matter.

您还应该确保您了解二进制浮点是如何工作的,并且它总是会导致看似“圆形”的值变得略微偏离 - 这对于大多数应用程序(包括您的应用程序)来说根本无关紧要,只要它发生在第 17 位十进制数字。另请参阅该链接以了解重要应用程序的替代方案。