Kitz Forum

Internet => Web Hosting & Web Design => Topic started by: chenks on March 01, 2019, 11:16:10 AM

Title: javascript - rounding to 2 decimal places
Post by: chenks on March 01, 2019, 11:16:10 AM
anyone any good with javascript?

i have a little script that counts the total of a column in a table

Code: [Select]
$(function () {
var TotalCoreProd = 0;
$("[id*=col01]").each(function () {
TotalCoreProd = TotalCoreProd + parseFloat($(this).html());
});
$("[id*=TotalCoreProd]").html(TotalCoreProd.toString());
});

problem is, it's outputing the value with about 20 decimal places.
i need to round this to 2 decimal places.
i believe ".tofixed(2)" should be used, but no matter where i try and place it, it ends up causing the code the fail completely.
Title: Re: javascript - rounding to 2 decimal places
Post by: scott1989uk on May 20, 2019, 08:12:21 PM
Bit late to the party but did you use toFixed with a capital F?

If not, it would cause a syntax error and wouldn’t run the code at all...
Title: Re: javascript - rounding to 2 decimal places
Post by: Weaver on June 28, 2019, 12:12:55 AM
So it was TotalCoreProd = TotalCoreProd + ParseFloat( … ).toFixed(2);  // ?
Title: Re: javascript - rounding to 2 decimal places
Post by: chenks on July 11, 2019, 01:12:32 PM
this was the working version

Code: [Select]
$(function () {
    var TotalCoreProd = 0,
        col1= $("[id*=col01]").filter(function(){
            return parseFloat( $(this).text() ) !== 0
        })
    col1.each(function () {
        TotalCoreProd = TotalCoreProd + parseFloat($(this).html());
    });
    $("[id*=TotalCoreProd]").html(TotalCoreProd.toFixed(2));
    $("[id*=AvgCoreProd]").html((TotalCoreProd/col1.length).toFixed(2));
});