Internet > Web Hosting & Web Design

javascript - rounding to 2 decimal places

(1/1)

chenks:
anyone any good with javascript?

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


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

--- End code ---

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.

scott1989uk:
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...

Weaver:
So it was TotalCoreProd = TotalCoreProd + ParseFloat( … ).toFixed(2);  // ?

chenks:
this was the working version


--- Code: ---$(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));
});

--- End code ---

Navigation

[0] Message Index

Go to full version