0

I have an array of objects and i need to inject the sum of some objects. So i have this :

var details=[{month:  1,equips:32.1, instals:12.6, softs:  6.7, manuts:6.2,  formacs:  9.7, total:0.0}]

An if i sum all the values to put the result in "total" i get a strange number (67.30000000000001) ...

I'm calculating "total" like this :

var i,nLines=details.length;
for(i=0;i<nLines;i++){
    details[i].total=(details[i].equips)+(details[i].instals)+(details[i].softs)+(details[i].manuts)+(details[i].formacs);
                }

And for some reason, on certain lines ( my array has more lines) my result has some strange decimals ... like the one that i mentioned ...

already tried parseFloat but i get the same weird result... and if i use .toFixed(1) i get " is not a function"

  • 2
    Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Álvaro González Jun 15 '17 at 15:11
  • The code you provided does not work. Your `details` array should end with `]` instead of `}` and your loop iterates through some variable called `detalhes` ? I'm sure this is a typo, but if you edit so that it is runnable, that might help. – pacifier21 Jun 15 '17 at 15:13
  • sorry, it was a typo and forgot to translate the loop variable – Nuno Marques Jun 15 '17 at 15:19
  • Welcome to floating point math! Always remember to present your numbers to the user in string format, using a fixed precision (number of decimal points). – drkstr101 Jun 15 '17 at 15:48

1 Answers1

0

There can be some problems using Math operations with float values in JavaScript. So you can simply wrap your result into function:

function roundFloat(number) {
  return parseFloat((number).toPrecision(10))
}

roundFloat(67.30000000000001); // 67.3
O. Borcuhin
  • 234
  • 2
  • 5