How to change a text variable to number value?

4

I have this segment of code, I would like someone to help me in transforming the variable P (in which it takes the attribute 'value') and transform it into number value for the sum.

$(document).ready(function(e) {         
    $('.pizzadisponivel').click(function(e){
        $(this).toggleClass('pizzaselecionada');
        var P = $('label').attr('value');
        Total+= P; 
        $("#teste").html('R$' + Total);
        alert(Total)
    });
    var Total = 0;      
});
    
asked by anonymous 03.12.2016 / 01:41

3 answers

10

I like the simplicity of % of unary% :

Total += +P;
// Variáveis começam com minúsculas,
// o ideal seria: total += +p;
    
03.12.2016 / 02:13
3

Use parseFloat , because parseInt will convert to integers and thus you will lose the cents of the value, it should look like this:

$(document).ready(function(e) {         
    $('.pizzadisponivel').click(function(e){
        $(this).toggleClass('pizzaselecionada');
        var P = $('label').attr('value');
        Total += parseFloat(P); 
        $("#teste").html('R$' + Total);
        alert(Total)
    });
    var Total = 0;      
});

If you need precision use .toFixed(2);

$(document).ready(function(e) {         
    $('.pizzadisponivel').click(function(e){
        $(this).toggleClass('pizzaselecionada');
        var P = $('label').attr('value');
        Total += parseFloat(P).toFixed(2); 
        $("#teste").html('R$' + Total);
        alert(Total)
    });
    var Total = 0;      
});

If you need a calculation to parse a value formatted with commas and decimal separators use this answer:

03.12.2016 / 01:52
2

Just use the parseInt () in the variable.

$(document).ready(function(e) {         
    $('.pizzadisponivel').click(function(e){
        $(this).toggleClass('pizzaselecionada');
        var P = parseInt($('label').attr('value'));//Mudança aqui
        Total+= P; 
        $("#teste").html('R$' + Total);
        alert(Total)
    });
    var Total = 0;      
});

Or if it is double / float , parseFloat ()

    
03.12.2016 / 01:51