How to change a text variable to number value?

Asked

Viewed 686 times

4

I have this segment of code, I’d like someone to help me turn the variable P (in which you take the attribute 'value' ) and turn 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;      
});

3 answers

10

I like the simplicity of + unary:

Total += +P;
// Variáveis começam com minúsculas,
// o ideal seria: total += +p;
  • Why the + in front of the 'p'? First I see it being using thus @bfvaretto.

  • 2

    It is a unary operator (has only one operand), which converts to the Number type.

3

Use parseFloat, for the parseInt will convert to integer and so will lose the pennies of value, should stay 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 parse a value formatted with commas and decimal separators use this answer:

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()

Browser other questions tagged

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