1

Possible Duplicate:
Elegant workaround for JavaScript floating point number problem

I need a workaround for the fact that Javascript can't do floating math reliably due to the IEEE 754 standard from 1985 it uses. Basically, what I need is a way to evaluate an expression like 5+3*(2+8/6). I'm thinking of doing it with strings and rolling my own functions for basic operations (+-*/%), but I was wondering first if you know of any library that does this already.

Community
  • 1
  • 1
pandronic
  • 631
  • 2
  • 9
  • 21
  • I know of the bignum libraries, but they are quite awkward to use and add even more complexity. I don't care about performance, I care about convenience for this particular project. Something like: calculate('0.5/5+1/5') => 0.3. Does something like this exist, or do I have to write my own library? That is the question. – pandronic Oct 22 '12 at 06:54
  • Coding an expression parser from infix to postfix notation, then feeding the postfix into a bignum library should be a lot easier than writing a complete expression parser and math routines on its own. There is a good discussion here: http://stackoverflow.com/questions/28256/equation-expression-parser-with-precedence – Jeremy J Starcher Oct 22 '12 at 07:27

1 Answers1

0

It depends on how big the numbers are. For small numbers (e.g. fewer than 14 significant digits), rounding to acceptable precision may do the job. e.g. given your example:

var n = 0.5 / 5 + 1 / 5;  // 0.30000000000000004

var p = Math.pow(10, 14); // where 14 is calculated based on the first
                          // significant digit and its relationship to
                          // the decimal place

n = Math.round(n * p) / p;  // 0.3

Calculating the power of 10 to use shouldn't be that hard. If you have large numbers, then life is more difficult (see existing libraries).

RobG
  • 142,382
  • 31
  • 172
  • 209
  • I've been doing this for sometime, but it feels kind of a hack and it makes code less readable and error prone. For applications where performance is not an issue, I'd pretty much rather have a library I can trust, to which I can feed simple expressions and get a correct result. I'm contemplating wiping out my own based on https://github.com/silentmatt/js-expression-eval and https://github.com/jtobey/javascript-bignum or writing my own from scratch if I have the time. – pandronic Oct 22 '12 at 11:19