JavaScript generating float with several decimal places

9

When creating an ordering system (quantity x value) I noticed that in some cases when adding broken values, JavaScript returns numbers with many more decimal places than expected.

Example:

(123*1.23)+(312*3.26) //retorna 1168.4099999999999 ao invés de 1168.41

Is this a common behavior in JavaScript? Does not the fact that I am calculating values with only two decimal places should limit the result to only two houses? Is there any way to make the behavior return the expected value (eg, 1168.41 )?

    
asked by anonymous 17.08.2014 / 21:18

1 answer

18

Yes, this is known behavior in the javascript and already discussed in other questions .

Suggestion:

var conta = (123*1.23)+(312*3.26);
var arredondado = parseFloat(conta.toFixed(2));

console.log(conta); // 1168.4099999999999 
console.log(arredondado); //1168.41 

jsFiddle: link

The .toFixed () rounds the number to the nearest decimal place and can choose the number of decimal places. The resulting format is string , hence the parseFloat ( ) also.

    
17.08.2014 / 21:23