0

I am trying to add this large decimal number together to get 9999999999.9999999999 but instead I am getting 10000000000.

Here is the code:

function add(x, y) {

    var filterFloat = function (value) {
      if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/
        .test(value))
        return Number(value);
    return NaN;
  }

    if (typeof x == 'string') {
    filterFloat(x);
    console.log(x);
  }; 
  if (typeof y == 'string') {
    filterFloat(y);
    console.log(y);
  };

  var z = filterFloat(x) + filterFloat(y);
  //var short = z.toFixed(4);
  //console.log(short);
  //return short.toString();
  //return z.toString();
  return z;
  var zz = z.toString();
  return zz;
  //console.log(typeof zz);

}

Here is the argument being passed:

add("1234567890.0987654321", "8765432109.9012345678");

See the fiddle below:

https://jsfiddle.net/emporio/gythd5dr/

  • This is not related to your code, if you assign 99999999999.999999999999 to a float in js, it will be approximated to 100000000000. Just type it in the console of chrome and press return. you have to do more that this to handle big numbers sum. Tip: for example, store all the digits in an array. – Massimiliano Carosi Jul 24 '16 at 21:30

2 Answers2

1

This is most probably floating-point precision at work. In general floating-point numbers as computed by modern CPUs are only approximately right and have lots of edge cases like the one you are experiencing. That's due to a finite length of the registers in your CPU.

If you need arbitrary precision, you'll need to fallback to a (much slower) library that handles it (or do it yourself manually of course).

Example: https://github.com/MikeMcl/bignumber.js

markusthoemmes
  • 3,080
  • 14
  • 23
0

Have you tried this so far?

https://shamim8888.wordpress.com/languages/bigdecimal-in-javascript/

I think that this might work for you. I used it before.

Aleksandar Đokić
  • 2,118
  • 17
  • 35