3

Simple maths with JS gets wrong when using decimals.

 console.log(.6+.6+.6) //1.7999999999999998

One possible solution could be multiply each number by a million and then divide it by a million, but seems is not efficient at all.

console.log(((.6*1000000)+(.6*1000000)+(.6*1000000))/1000000) //1.8

Is there any "proper" way to sum with decimals in JS without a library?

If it isn't must recommendations are to use other libraries like https://github.com/MikeMcl/bignumber.js/ or https://github.com/MikeMcl/decimal.js/ or https://mathjs.org/ which one you recommend?

At the moment I believe would be better to multiply only by 1000000 and divide it later, this way I do not have to install a whole module for the "basic" operations... but again, basic operations in JS are not basic.

fp007
  • 412
  • 1
  • 4
  • 18

1 Answers1

3

Take a look for Dealing with float precision in JS

This is my fix:

console.log( parseFloat((.6+.6+.6).toFixed(2)) )

// Or

var a = 0.6;
var b = 0.6;
var c = 0.6;

var R = parseFloat( (a + b + c).toFixed(2) );

console.warn("Result :", R)


// Final solution is method 
// Array used for args[]

function sumFloats (items) {

  var R = 0;

  for (var x = 0;x < items.length;x++) {
  console.warn(">>: ", items[x]);
  R += parseFloat( (items[x]).toFixed(2) );
  }

  R = parseFloat(R.toFixed(2));
  console.warn("Result from function: ", R);
  return R;

}

var a = 0.6;
var b = 0.6;
var c = 0.6;
var ResultFromFunc = sumFloats ([0.6, 0.6, 0.6]);
var ResultFromFunc2= sumFloats ([a, b, c]);

toFixed(dec). will return string but with good format then just parse to the float to get number again.

Update:

function sumFloats (items) {

  var R = 0;

  for (var x = 0;x < items.length;x++) {
  //console.warn(">>: ", items[x]);
  R += parseFloat( (items[x]).toFixed(2) );
  }

  R = parseFloat(R.toFixed(2));
  //console.warn("Result from function: ", R);
  return R;

}

// console.log( 33.4 + 33.3 + 33.3 ) // = 99.9999999 

// test 
var a = 33.4;
var b = 33.3;
var c = 33.3;

console.log( "a + b + c = ",  a + b + c )
console.log( "a + c + b = ",  a + c + b )
 
console.log( "c + b + a = ",  c + b + a )  
console.log( "c + a + b = ",  c + a + b )

console.log( "b + c + a = ",  b + c + a )
console.log( "b + a + c = ",  b + a + c )

console.log( "sum -> ", sumFloats([a,b,c]) )
console.log( "sum -> ", sumFloats([a,c,b]) )
console.log( "sum -> ", sumFloats([c,b,a]) )
console.log( "sum -> ", sumFloats([c,a,b]) )
console.log( "sum -> ", sumFloats([b,c,a]) )
console.log( "sum -> ", sumFloats([b,a,c]) )
Nikola Lukic
  • 4,001
  • 6
  • 44
  • 75
  • 1
    it can solve the problem but the mysterious thing is why 33.4+33.3+33.3 = 99.9999999 in js instead of 100 lol – SKLTFZ Jun 17 '22 at 03:59
  • You can read about "Dealing with float precision" . It is not big deal you can use also https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision . – Nikola Lukic Jun 17 '22 at 20:17