Kitz ADSL Broadband Information
adsl spacer  
Support this site
Home Broadband ISPs Tech Routers Wiki Forum
 
     
   Compare ISP   Rate your ISP
   Glossary   Glossary
 
Please login or register.

Login with username, password and session length
Advanced search  

News:

Author Topic: javascript - rounding to 2 decimal places  (Read 2442 times)

chenks

  • Reg Member
  • ***
  • Posts: 693
javascript - rounding to 2 decimal places
« 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.
Logged

scott1989uk

  • Just arrived
  • *
  • Posts: 9
Re: javascript - rounding to 2 decimal places
« Reply #1 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...
Logged

Weaver

  • Addicted Kitizen
  • *****
  • Posts: 7738
  • Retd sw dev; A&A; 4 × 7km ADSL2; IPv6; Firebrick
Re: javascript - rounding to 2 decimal places
« Reply #2 on: June 28, 2019, 12:12:55 AM »

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

chenks

  • Reg Member
  • ***
  • Posts: 693
Re: javascript - rounding to 2 decimal places
« Reply #3 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));
});
Logged
 

anything