Javascript generating float with multiple decimals

Asked

Viewed 85,227 times

17

When creating an order calculation system (quantity x value) I realized that in some cases when adding broken values Javascript returns numbers with many other decimal places more 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? The fact that I am calculating values with only two decimal places should not limit the result also to only two houses? Is there any way to make the behavior return the expected value (eg.: 1168.41)?

1 answer

35


Yes, this is a known behavior in 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: http://jsfiddle.net/p770xhvr/

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

  • Here the function does not round... because it will?

  • @Diêgocorreiadeandrade my example works? if you don’t make a video or image to be able to see the error?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.