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

发布于 2024-09-06 06:19:20 字数 407 浏览 0 评论 0原文

我有一个双值问题,我需要存储在 android 宿主的 sqlite 数据库中。由于这些双精度值代表 GPS 值(纬度和经度),因此我确实需要精确到逗号后的第 9 个数字的绝对精度。

现在我有一个像这样的表:

CREATE TABLE x REAL lng;

并插入像这样的东西(硬编码):

INSERT INTO x lng = '1.0';

当从该表读取 lng 到某个(java)双变量时,我得到一个像“0.999956837”这样的值 - 这使得这些值对我来说非常无用。

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

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 NEED an absolute precision down to the 9th number after the comma.

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.

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)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

公布 2024-09-13 06:19:20

SQLite 是无类型,这意味着所有表示形式都以文本形式编写,可能包装器 api 会进行一些转换不知道你会得到这些结果。

如果您需要将数据存储为字符串这样做。

当您读出双精度数时请确保以正确的格式保存,您可以在列上使用getDouble

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.

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.

秋凉 2024-09-13 06:19:20

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

您还应该确保您了解二进制浮点如何工作,并且它会总是会导致看似“舍入”的值稍微偏离——这对于大多数应用程序(包括您的应用程序)来说并不重要,只要它出现在小数点后第 17 位即可。另请参阅该链接,了解重要应用程序的替代方案。

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). Just make sure you never end up using float, because that has only about 7 digits of precision.

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. See that link also for alternatives for applications where it does matter.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文