Search code examples
jqueryjquery-calculation

Result format right Jquery Function


I have a code fast and quiet, but results in some calculations are formatted very large, including, the value obtained does not enter the calculation. How to do this see the right result?

I would like the result of the calculation (3 * 2215.40) was 3 646.20 and non 3.6450000000000005.

How?

Code - http://jsfiddle.net/bruno_aw/M7JZu/

$(".calc_cub").on("keyup", ".qtd", function(){
    var valorCub = $("#CUB").text();        
    var number = parseFloat(valorCub);  
    var qtd = +$(this).val();
    $(".total").text(number * qtd).val().toFixed(2);
});

Solution

  • You need to first get the number out of the text. You are also calling .val() after you set the text on .total - which all you need to really do is $(".total").text((number * qtd).toFixed(2));

    $(".calc_cub").on("keyup", ".qtd", function () {
        var valorCub = $("#CUB").text().split(' '); // returns ["Valor", "CUB", "R$", "1,215.40"]
        var number = parseFloat(valorCub[valorCub.length - 1].replace(',','')); // get last one in array and remove comma
        var qtd = +$(this).val();
        $(".total").text((number * qtd).toFixed(2));
    });
    

    http://jsfiddle.net/GMjjc/