Firestore增量浮点问题 [英] Firestore increment floating points issue

查看:72
本文介绍了Firestore增量浮点问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,我知道关于此问题还有其他一些问题,但没有真正的答案.

Note that I know there have been some other questions, but no real answer, on SO, regarding this issue.

因此,自实现增量字段值以来发生的事情是,在递增浮点数时,大多数情况下,您会得到一打小数而不是实际数字.

So, what has been happening since the increment field value was implemented, is that when incrementing floating numbers, most of the time you'll get a dozen decimals instead of the actual number.

// incrementing 0, with 0.1, 11 times, returns 1.0999999999999999
Math.round( 1.0999999999999999 * 100 + Number.EPSILON ) / 100 

这返回正确的数字...所以我想知道,这不能在处理Firestore中的实际值增加的方法中实现吗?

This returns the correct number ... so I wonder, can't this be implemented inside the method that deals with incrementing the actual value inside Firestore ?

问题是,当我想显示基于语言环境的数字时,我使用以下内容:

Problem is, when I want to show numbers locale-based, I use the following:

number.toLocaleString( undefined, { minimumFractionDigits: 2 })

这将显示1.09这是错误的,客户对他们的收入感到困惑.

That would show 1.09 which is wrong, and customers get confused about their earnings.

在接收到客户端数据之后,除了处理数据外还要做些什么?

What's to be done aside manipulating the data after receiving it client side?

另一个副作用是,当使用递增大的负值时,有时由于某种原因,您会在Firestore的值中获取该+e,并且在服务器端获取该值时(至少使用PHP Admin) SDK),数字以字符串而不是整数结尾.

Another side effect of this is that when using incrementing a big negative value, sometimes, for some reason, you get that +e inside your value in Firestore, and when fetching it server-side ( at least with the PHP Admin SDK ), the number ends up as a string, and not as an integer.

推荐答案

根据 IEEE 754 格式存储浮点数.请花一些时间来了解这种格式的含义.基本上,您不能指望浮点数来保持您指定的精确度,因为某些数字格式可能无法做到这一点.存储数字时,您可以期望会有一些小的变化.在堆栈溢出的此处已经可以找到关于这种行为的很好的总结:

According to the documentation, Cloud Firestore stores floating point numbers in IEEE 754 format. Please take some time to understand what this format implies. Basically, you can't count on floating point number to retain exactly the accuracy that you've specified, as the format can't possibly do that for some numbers. You can expect some small variation when the number is stored. A good summary of this type of behavior can already be found here on Stack Overflow:

如果必须保留数值精度,请考虑使用一个有助于加载和存储具有所需精度的数字的库.几乎所有的金融应用程序都会这样做,因为IEEE 754可以有效地丢失数据,以便将数据压缩到较小的大小.

If you must retain numerical accuracy, look into using a library that will help load and store numbers that have the accuracy you need. Pretty much all financial application will do something like this, as IEEE 754 can effectively lose data in order to compress the data down to a small size.

这篇关于Firestore增量浮点问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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