Solved

Adding thousands comma separator to Javascript code

Posted on 2007-11-14
5
4,061 Views
Last Modified: 2008-02-01
Hi there

Could anyone please assist with code below.  I want the results to come up with thousands comma separator (i.e. 10,000) with no decimal places.  I have found various bits of code but I have no idea how to implement them.  Thanks.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
<link href="/style.css" rel="stylesheet" type="text/css" />
<title>Calc amounts</title>
<script type="text/javascript">
function figure(frm) {
  var num1 = IsNum(frm.val1.value);
  var num2 = IsNum(frm.val2.value);
  var num3 = IsNum(frm.val3.value);
  var num4 = IsNum(frm.val4.value);
  var num5 = IsNum(frm.val5.value);
  var str1 = "The figure we calculate is $";
  var total1 = num1 + num2 + num3 + (2 * num4) + (2 * num5);
  var str2 = "<br>The alternative figure we calculate is $";
  var total2 = num1 + num2 + num3 + num4 + num5;
  document.getElementById('figure').innerHTML =  str1 + total1.toFixed(0)+
str2 + total2.toFixed(0);
}
function IsNum(val) {
      val = parseInt(val,10);
      return (val == '' || isNaN(val))? 0 : val;
}
</script>
</head>

<body>
<h3>Let's figure it</h3>

<form name="form1" action="" method="post">
<input type="text" name="val1" size="3" /> + <input type="text" name="val2" size="3" /> + <input type="text" name="val3" size="3" /> + (2 x <input type="text" name="val4" size="3" />) + (2 x <input type="text" name="val5" size="3" />) =
<br /><br />
<input type="button" value="Calc" onclick="figure(this.form);" />
</form>

<div id="figure"></div>

</body>
</html>
0
Comment
Question by:dvsuk
5 Comments
 
LVL 41

Expert Comment

by:HonorGod
ID: 20282091
0
 
LVL 25

Expert Comment

by:James Rodgers
ID: 20282304
smething like this, takes a number and adds thousands and decimals if specified, currently formatted for french style

<script>
function FormatWithDecimals (n,decimals) {
      decimals=(decimals>=0?decimals:2)
    var t = Math.floor(n*Math.pow(10,decimals)+0.5).toString();
    while (t.length < decimals+1) t = "0"+t;
          var i = t.length-decimals;
      if(decimals)
          t = t.substr(0,i)+","+t.substr(i); // insert decimal separator (a dot or comma)
    for (i -= 3; i > 0; i -= 3)
            t = t.substr(0,i)+"."+t.substr(i); // insert thousands separators (commas or dots)
    return t;
}

      alert(FormatWithDecimals (123456789));
      alert(FormatWithDecimals (1234567.89,2));
      alert(FormatWithDecimals (123456789,0));
</script>
0
 
LVL 10

Accepted Solution

by:
js_vaughan earned 500 total points
ID: 20282320
Add this function to your header:

function addCommas(val) {
    var regEx = /(\d+)(\d{3})/;
    while (regEx.test(val)) {
        val = val.replace(regEx, '$1' + ',' + '$2');
    }
    return val;
}

And update this line to read like so:

document.getElementById('figure').innerHTML =  str1 + addCommas(total1.toFixed(0)) + str2 + addCommas(total2.toFixed(0));
0
 
LVL 10

Expert Comment

by:js_vaughan
ID: 20282414
Also, using your current methods, all the decimals are being dropped before any math is being done.  so even if someone were to put "0.5" in for the last two (X2) blocks... that should equal an extra 2 dollars... If this is on purpose, disregard this comment.  Otherwise, if you just want to remove the decimals at the end I recommend:

// replace parseInt with parseFloat
function IsNum(val) {
      val = parseFloat(val,10);
      return (val == '' || isNaN(val))? 0 : val;
}

// Round your dollars and comma-format before output
document.getElementById('figure').innerHTML =  str1 + addCommas(Math.round(total1)) + str2 + addCommas(Math.round(total2));
0
 

Author Comment

by:dvsuk
ID: 20282460
js_vaughan - Spot on.  Thank you!
0

Featured Post

Active Directory Webinar

We all know we need to protect and secure our privileges, but where to start? Join Experts Exchange and ManageEngine on Tuesday, April 11, 2017 10:00 AM PDT to learn how to track and secure privileged users in Active Directory.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question