Percentage calculation with JS

Asked

Viewed 23,182 times

3

I’m setting up a function to do the calculation using percentage. My online test works.

http://jsfiddle.net/pfrk0v0s/

$(document).ready(function () {
        valorTotaldaNota    = "1.000,00";
        valorTotaldaNota    = valorTotaldaNota.replace(",", "");
        adValorem           = "0.33";
        gris                = "0.20";

        v1 = valorTotaldaNota * adValorem / 100;
        v2 = valorTotaldaNota * gris / 100;


        alert(  v1 + v2 );


});

But in my local file, the calculation is not correct and appears a lot of zero in freight. Ex: 0.0087

$(document).ready(function () {
    $(".seguro").click(function() {

            valorTotaldaNota    = $("#valorTotaldaNota").val();
            valorTotaldaNota    = (valorTotaldaNota.replace(",", ""));
            adValorem           = ($("#adValorem").val());
            gris                = <?php echo $gris; ?>

            v1 = valorTotaldaNota * adValorem / 100;
            v2 = valorTotaldaNota * gris / 100;

            $("#valordoSeguro").val( v1 + v2 );

    }); 
});
  • James put together an answer with a more elaborate explanation. I hope it will be useful.

2 answers

3

When you have a string '1.000,00' and you do '1.000,00'.replace(",", ""); this will give

'1.00000' // tipo string

Luckily, in Javascript, '1.00000' * 5 gives 5. Although 1.00000 be a string and not a number. Javascript does not use the comma, uses only the point to divide the decimal part. There '1.00000' is actually read as 1.

How then?

To do arithmetic operations you have to be working with numbers, not strings. You can use a function to clear the input and return a number. She must be able to treat both cases where the comma divides the decimal part as 1.000,00 but also the other values that you’ve placed as "0.33"...

function conversor(str){
    if (typeof str == 'number') return str;
    var nr;
    var virgulaSeparaDecimais = str.match(/(,)\d{2}$/);
    if (virgulaSeparaDecimais) nr = str.replace(/\./g, '').replace(',', '.')
    else nr = str.replace(',', '');
    return parseFloat(nr);
}

A suggested code would be:

function conversor(str) {
    if (typeof str == 'number') return str;
    var nr;
    var virgulaSeparaDecimais = str.match(/(,)\d{2}$/);
    if (virgulaSeparaDecimais) nr = str.replace(/\./g, '').replace(',', '.')
    else nr = str.replace(',', '');
    return parseFloat(nr);
}

$(document).ready(function () {
    $(".seguro").click(function () {
        var valorTotaldaNota = conversor($("#valorTotaldaNota").val());
        var adValorem = conversor($("#adValorem").val());
        var gris = conversor( <? php echo $gris; ?> )

        var v1 = valorTotaldaNota * adValorem / 100;
        var v2 = valorTotaldaNota * gris / 100;

        $("#valordoSeguro").val(v1 + v2);
    });
});

Notice you were omitting var in the variable declaration. Avoid this as you are exporting to the global space and can unintentionally re-write other variables.

A regex (,)\d{2}$ looking for a comma (,) followed by 2 digits \d{2} which are at the end of string $. If your numbers have variant decimal part the thing becomes more complex. In that case tell me to correct here.

  • this error converter when using 1,000,000.00 only takes the first point(.)

  • 1

    @Juniorramoty you’re right! I corrected, thank you :)

2

I found the problem. One more conversion needed.

valorTotaldaNota    = valorTotaldaNota.replace(".", "");
valorTotaldaNota    = valorTotaldaNota.replace(",", ".");

First, take the point and then in place of the comma put the point.

Now it worked.

Browser other questions tagged

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