- JavaScript's lack of mathematical precision
- PERL workaround
- Related links

While JavaScript is quickly becoming the lingua franca of the web, this general purpose language contains built-in limitations which restrict its use to simple applications. For example, I recently tried to write a Diffie-Hellman Demo in JavaScript but detected problems during testing which I traced to limited math precision. Check out these comparisons:

JavaScript | Math.pow(7,18) | 1628413597910449 | correct |

Calculator | 7^18 | 1628413597910449 | correct |

JavaScript | Math.pow(7,19) | 11398895185373144 | incorrect |

Calculator | 7^19 | 11398895185373143 | correct |

JavaScript | Math.pow(7,20) | 79792266297612000 | incorrect |

Calculator | 7^20 | 79792266297612001 | correct |

JavaScript | Math.pow(7,21) | 558545864083284030 | incorrect |

Calculator | 7^21 | 558545864083284007 | correct |

- Many junior programmers think this problem is related to internal rounding but it is actually a limitation due to float-point math.
- Many seasoned programmers are surprised to learn that all JavaScript numbers (floating point or not) are stored in 64-bit floating point format (similar to JAVA's double) and there are no official alternative data types.
- References:
- JavaScript workarounds:
- https://github.com/jhs/bigdecimal.js/ (Big Decimal)
- https://github.com/silentmatt/javascript-biginteger/ (Big Integer)
- http://www.leemon.com/crypto/BigInt.html (Big Int)
- http://www-cs-students.stanford.edu/~tjw/jsbn/ (Big Number)

- Other workarounds:
- for client side software, switch to JAVA
- for server side software, switch to PERL

```
Legend: <sr> = system response
<ur> = user response
<sr> $
<ur> type bigint_demo.pl
#
# title: bigint_demo.pl
#
use bigint; # use bigint after this point
$x = 7 ** 19; # x = 7^19
printf("%s\n",$x); # "%s" because other formats bomb
<sr> $
<ur> perl bigint_demo.pl
<sr> 11398895185373143 ! correct
<ur> $
```

Back to Home

Neil Rieck

Kitchener - Waterloo - Cambridge, Ontario, Canada.