How to subtract decimal numbers?

3

I made a function to do FadeOut on <div> once I finished loading the page but I can not get the exact value of the end of FadeOut (that would be 0) always give me a number like this: 0.009999999999999247; / p>

How can I do to subtract correctly and get 0?

function fadeOut(id){
    //pega o elemento da página
    obj = document.getElementById(id);
    //seta a opacidade como 0
    obj.style.opacity = 1.00;

    fazFadeOut = function (){
        if(obj.style.opacity != 0){  
            var atual = Number(obj.style.opacity);   
            var newopac = atual - Number(0.01);
            obj.style.opacity = String(newopac);    
            if(obj.style.opacity == 0){
                obj.style.display = 'none';
            }
            setTimeout('fazFadeOut()', 10);
        }
    }
    fazFadeOut();
}

EXAMPLE working

    
asked by anonymous 19.02.2014 / 05:10

2 answers

5

Number in Javascript is a floating point ( link ) and, according to the link "as accurate as possible" . Therefore:

var soma = 0.06 + 0.01
// soma fica com o valor de 0.06999999999999999

One solution to this is to round the value using toFixed (NumberDigitsNodeDecimal)

var soma = (0.06 + 0.01).toFixed(2);
// soma fica com o valor de 0.07

var maisCasas = (0.06 + 0.01).toFixed(5);
// maisCasas fica com o valor de 0.07000
    
19.02.2014 / 05:27
2

You can use Math.floor() to round down by getting the 0 you want:

But you want the decimal value, so you should only use fewer decimal places, because javascript is no longer accurate after a few decimal places, so:

window.onload = function(){
//quando o documento terminar de carregar esconde a div
    setTimeout(function(){
        fadeOut('load');
        document.getElementById('content').style.webkitFilter = 'none';
    },1000);
};

function fadeOut(id){
    //pega o elemento da página
    obj = document.getElementById(id);
    //seta a opacidade como 0
    obj.style.opacity = 1.00;

    fazFadeOut = function (){
        if(obj.style.opacity !== 0){     
            var atual = Number(obj.style.opacity);   
            var newopac = atual - Number(0.01).toFixed(x);//onde x seria o numero de casas decimais que você quer.
            obj.style.opacity = String(newopac);    
            if(obj.style.opacity === 0){
                obj.style.display = 'none';
            }
            setTimeout(fazFadeOut, 10);
        }
    };
    fazFadeOut();
}

Note:

I have corrected some warnings that your JSBin has accused, the code would look like it's already corrected.

Changes: Comparisons should be made with === and !== in this context, and also a few semicolons were missing. Something else important does not use setTimeout("fazFadeOut()", 10); never . You should pass the function itself, which would be using setTimeout(fazFadeOut, 10);

    
19.02.2014 / 05:24