简体   繁体   English

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

[英]storing double values in SQLite: how to ensure precision?

i have a problem with double values i need to store in an android homed sqlite database. 我有一个问题,我需要存储在android homed sqlite数据库中的双值。 since these double values represent gps values (lat & lng), i really NEED an absolute precision down to the 9th number after the comma. 因为这些double值代表gps值(lat&lng),所以我真的NEED一个绝对精度,直到逗号后的第9个数字。

now i have a table like this: 现在我有一个这样的表:

CREATE TABLE x REAL lng;

and insert sth (hardcoded) like: 并插入sth(硬编码),如:

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)? 有没有办法强制执行我需要的精度,除了将值存储为“文本”字段(什么会使昂贵的演员需要)或将它们存储为整数(意味着我需要在每次写/读操作时乘以/除)?

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 getDouble on the column. 就在您读出double时,请确保以正确的格式保存,您可以在列上使用getDouble

double has 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). double有大约17个十进制数字的精度,所以如果你需要9位数,那么应该没有问题(假设你没有对这些值进行任何复杂的计算)。 Just make sure you never end up using float , because that has only about 7 digits of precision. 只要确保你永远不会使用float ,因为它只有大约7位数的精度。

You should also make sure you understand how binary floating-point works , and that it will always result 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. 您还应该确保理解二进制浮点的工作方式 ,并且它总是会导致看似“圆”的值略微偏离 - 这对于大多数应用程序(包括您的)来说无关紧要,只要它发生在某个地方。第17个十进制数字。 See that link also for alternatives for applications where it does matter. 请参阅该链接,了解其重要性的应用程序的替代方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM