Some operations are overflowed in javascript [duplicated]

3

Good afternoon. guys I have the following problem. with a simple addition operation the following happens to me:

99.92+0.04
99.96000000000001

I do not know why that 1 is added at the end. This makes the results of operations do not give me exact.

    
asked by julian rincon 28.10.2016 в 23:22
source

2 answers

1

You can do it using the function parseFloat and then limiting the number of decimals that you will show in your result:

var suma = parseFloat('99.92') + parseFloat('0.04');
alert(suma.toFixed(2));

Or you could directly limit the number of characters to two in case you did not want to take them as Float and just out to show them:

var suma = 99.92 + 0.04;
alert(suma.toFixed(2));

This would be to solve the "error". In case you want more detailed answers about why this happens, I'll give you a very good Stackoverflow question in English with very complete answers: Is floating point math broken?

    
answered by 28.10.2016 / 23:35
source
1

Try the following function, in my case it was the option that worked for me:

Number.prototype.roundDecimal = function (d) {
    if (!d || d == 0 || d == null || typeof d === 'undefined') { d = 2; };
    num = this;
    num = num * Math.pow(10, d)
    num = Math.round(num)
    num = num / Math.pow(10, d)
    return num
}

Then you only use the function something like this:

var num = 99.92+0.04; 

num = num.roundDecimal() //Si no le pasas parametro toma 2 decimales despues del punto.

This has worked for me in a billing application (decimals management) that I currently have in production.

It's an adaptation of this code .

    
answered by 29.10.2016 в 00:41