Arbitrary precision of Float numbers in JavaScript

I have some inputs on my site that represent floating point numbers containing up to ten precision digits (in decimal). At some point, in the client-side verification code, I need to compare a pair of these values ​​to make sure they are equal or not, and here, as you would expect, the internals of IEEE754 make this simple check unsuccessful with such things (2.0000000000 = = 2.0000000001) = true.

I can break the floating point number into two long points for each side of the point, make each side 64-bit long and do my comparisons manually, but it looks so ugly!

Any decent Javascript library for handling arbitrary (or at least guaranteed) precision floating point numbers in Javascript?

Thanks in advance!

PS: GWT-based solution has ++

+5
javascript floating-point gwt
Jan 21 '10 at 11:18
source share
2 answers

There is a GWT-MATH library at http://code.google.com/p/gwt-math/ .

However, I warn you, this is a GWT jsni java-> javascript overlay automatic java.BigDecimal conversion (actually old com.ibm.math.BigDecimal).

It works, but quickly it is not. (Do not bend, he will fit into a good project for 70 thousand).

At my workplace, we are working on a fixed point in a simple decimal code, but it’s not worth releasing anything. :(

+1
Jan 21 '10 at 15:25
source share

Use an arbitrary integer integer library such as silentmatts javascript-biginteger , which can store and evaluate with integers of any arbitrary size.

Since you need ten decimal places, you need to store the value of n as nΓ—10^10 . For example, save 1 as 10000000000 (ten zeros), 1.5 as 15000000000 (nine zeros), etc. To display the value for the user, simply place the decimal point before the tenth (and then cut off any trailing zeros if you want).

Alternatively, you could store the numerator and denominator as large integrators, which would then allow you to make arbitrarily accurate fractional values ​​(but be careful - fractional values ​​have a very high speed).

+1
Nov 08 '10 at
source share



All Articles