Home Search Member List Faq Register Login  
JavaScript Tips
Format number

Thread Starter: Karamasoft   Started: 09-04-2007 7:09 PM   Replies: 0
 Karamasoft Support Forums » General Discussions » JavaScript Tips » Format number
 Printable Version    « Previous Thread   Next Thread »
  04 Sep 2007, 7:09 PM
Karamasoft is not online. Last active: 5/8/2018 10:36:45 AM Karamasoft

Top 10 Posts
Joined on 09-05-2004
Posts 6,820
Format number

You can use the following method to format your numbers or currency values. It takes four arguments: the number to format, the number of decimal places, a Boolean to indicate whether zeros should be appended, and a Boolean to indicate whether commas should be inserted to separate thousands.

function FormatNumber(num, decimalPlaces, appendZeros, insertCommas) {
 var powerOfTen = Math.pow(10, decimalPlaces);
 var num = Math.round(num * powerOfTen) / powerOfTen;
 if (!appendZeros && !insertCommas) {
  return num;
 }
 else {
  var strNum = num.toString();
  var posDecimal = strNum.indexOf(".");
        if (appendZeros) {
      var zeroToAppendCnt = 0;
      if (posDecimal < 0) {
       strNum += ".";
       zeroToAppendCnt = decimalPlaces;
      }
      else {
       zeroToAppendCnt = decimalPlaces - (strNum.length - posDecimal - 1);
      }
      for (var i = 0; i < zeroToAppendCnt; i++) {
       strNum += "0";
      }
  }
     if (insertCommas && (Math.abs(num) >= 1000)) {
      var i = strNum.indexOf(".");
      if (i < 0) {
       i = strNum.length;
            }
      i -= 3;
      while (i >= 1) {
       strNum = strNum.substring(0, i) + ',' + strNum.substring(i, strNum.length);
       i -= 3;
      }  
     }
  return strNum;
 }
}


  
 Page 1 of 1 (1 items)
Karamasoft Support Forums » General Discussions » JavaScript Tips » Format number

You can add attachments
You can post new topics
You can reply to topics
You can delete your posts
You can edit your posts
You can create polls
You can vote in polls
Forum statistics are enabled
Forum is unmoderated

© 2002-2018 Karamasoft LLC. All rights reserved.