»
EnglishFrenchVietnamese

Print - Simple JavaScript Number Formatter - JavaScriptBank.com

Full version: jsB@nk » Form » Simple JavaScript Number Formatter
URL: https://www.javascriptbank.com/simple-javascript-number-formatter.html

Simple JavaScript Number Formatter © JavaScriptBank.comThis JavaScript code example provides us two functions to clean up and format numbers quite nicely.One JavaScript check number function will take any decimal number, negative or positive, and formats it by adding commas every three digits. The other JavaScript number format function can strip any non-numeric characters from a string leaving you with a valid decimal number. It also considers the minus sign and the period to be numeric and will not strip them unless the minus sign is not at the beginning of the number or there is more than one period.These JavaScript functions make use of regular expressions to do the heavy lifting.

Full version: jsB@nk » Form » Simple JavaScript Number Formatter
URL: https://www.javascriptbank.com/simple-javascript-number-formatter.html



JavaScript
<script type="text/javascript">// Created by: Justin Barlow | http://www.netlobo.com/// This script downloaded from www.JavaScriptBank.com// This function formats numbers by adding commasfunction numberFormat(nStr){  nStr += '';  x = nStr.split('.');  x1 = x[0];  x2 = x.length > 1 ? '.' + x[1] : '';  var rgx = /(\d+)(\d{3})/;  while (rgx.test(x1))    x1 = x1.replace(rgx, '$1' + ',' + '$2');  return x1 + x2;}// This function removes non-numeric charactersfunction stripNonNumeric( str ){  str += '';  var rgx = /^\d|\.|-$/;  var out = '';  for( var i = 0; i < str.length; i++ ){    if( rgx.test( str.charAt(i) ) ){      if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||             ( str.charAt(i) == '-' && out.length != 0 ) ) ){        out += str.charAt(i);      }    }  }  return out;}</script>


HTML
<div>numberFormat():<br><form method="get" onsubmit="javascript:return false;"><input type="text" onkeyup="javascript:document.getElementById('numFormatResult').innerHTML = numberFormat( this.value );"><input type="reset" value="clear"></form><span id="numFormatResult"></span><br><br>stripNonNumeric():<br><form method="get" onsubmit="javascript:return false;"><input type="text" onkeyup="javascript:document.getElementById('numStripResult').innerHTML = stripNonNumeric( this.value );"><input type="reset" value="clear"></form><span id="numStripResult"></span><br><br>stripNonNumeric() then numberFormat():<br><form method="get" onsubmit="javascript:return false;"><input type="text" onkeyup="javascript:document.getElementById('numBothResult').innerHTML = numberFormat( stripNonNumeric( this.value ) );"><input type="reset" value="clear"></form><span id="numBothResult"></span></div>