简体   繁体   English

任意精度JavaScript上的浮点数

[英]Arbitrary precision Float numbers on JavaScript

I have some inputs on my site representing floating point numbers with up to ten precision digits (in decimal). 我的网站上有一些输入表示浮点数,最多十位精度数字(十进制)。 At some point, in the client side validation code, I need to compare a couple of those values to see if they are equal or not, and here, as you would expect, the intrinsics of IEEE754 make that simple check fails with things like (2.0000000000==2.0000000001) = true. 在某些时候,在客户端验证代码中,我需要比较其中的几个值以查看它们是否相等,并且在这里,正如您所期望的那样,IEEE754的内在函数使得简单的检查失败了(如( 2.0000000000 == 2.0000000001)= true。

I may break the floating point number in two longs for each side of the dot, make each side a 64 bit long and do my comparisons manually, but it looks so ugly! 我可以打破点的每一边的两个长点的浮点数,使每一边长64位并手动进行比较,但它看起来很难看!

Any decent Javascript library to handle arbitrary (or at least guaranteed) precision float numbers on Javascript? 任何体面的Javascript库来处理Javascript上的任意(或至少保证)精度浮点数?

Thanks in advance! 提前致谢!

PS: A GWT based solution has a ++ PS:基于GWT的解决方案有一个++

There is the GWT-MATH library at http://code.google.com/p/gwt-math/ . http://code.google.com/p/gwt-math/上有GWT-MAT​​H库。

However, I warn you, it's a GWT jsni overlay of a java->javascript automated conversion of java.BigDecimal (actually the old com.ibm.math.BigDecimal). 但是,我警告你,这是java.BigDecimal的java-> javascript自动转换的GWT jsni重叠(实际上是旧的com.ibm.math.BigDecimal)。

It works, but speedy it is not. 它有效,但速度不快。 (Nor lean. It will pad on a good 70k into your project). (也不精益。它会在你的项目中填上70k)。

At my workplace, we are working on a fixed point simple decimal, but nothing worth releasing yet. 在我的工作场所,我们正在研究一个简单的十进制小数点,但没有什么值得发布的。 :( :(

Use an arbitrary precision integer library such as silentmatt's javascript-biginteger , which can store and calculate with integers of any arbitrary size. 使用任意精度整数库,例如silentmatt的javascript-biginteger ,它可以使用任意大小的整数进行存储和计算。

Since you want ten decimal places, you'll need to store the value n as n×10^10 . 由于您需要十位小数,因此您需要将值n存储为n×10^10 For example, store 1 as 10000000000 (ten zeroes), 1.5 as 15000000000 (nine zeroes), etc. To display the value to the user, simply place a decimal point in front of the tenth-last character (and then cut off any trailing zeroes if you want). 例如,将1存储为10000000000 (十个零), 1.515000000000 (九个零)等。要向用户显示值,只需在最后一个字符前面放置一个小数点(然后切掉任何尾随)如果你想要零)。

Alternatively you could store a numerator and a denominator as bigintegers, which would then allow you arbitrarily precise fractional values (but beware – fractional values tend to get very big very quickly). 或者你可以将分子和分母存储为大整数,这样就可以得到任意精确的小数值(但要注意 - 小数值往往非常快)。

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

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