Archive for March, 2009

Javascript - Thousand separator for numbers

Monday, March 30th, 2009

As a business application, it is always dealing with big number which can up to millions or billons. The numbers to be entered are required to be formatted using thousand separator, like 1000000 formatted to 1,000,000.

There are lots of way to archieve this.One common way is using textfield event attribute “onblur”, once the textfield loses focus,format the number in textfield.
But i wrote my own script which can allow the number to be formatted in instant just like Calculator.

<- html ->

<input type=”text” name=”num” style=’text-align:right’ onkeyup=”commas(this)”/>

<- javascript ->

function formatNum(obj){
var current=obj.value;
var after=current;

current=current.replace(/,/g,”");
var decimalpoint=current.lastIndexOf(”.”);

var n;
var d;
if(decimalpoint>=0){
var f=current.split(”.”);
d=f[1];
n=f[0];
}
else{
n=current;
}

var index=parseInt((n.length-1)/3);
if(index!=0){
var prefixIndex=n.length-index*3;
after=n.substr(0,prefixIndex)+”,”+n.substr(prefixIndex,3);
for(var i=2;i<=index;i++){
after+=”,”+n.substr(prefixIndex+3*(i-1),3);
}

if(decimalpoint>=0){
after+=”.”+d;
}
}
obj.value=after;
}

Basically the logic is to calculate how many separator needed, split numbers into parts and add separator into each part.

I tested on FF3, IE7, Safari 4, Google Chrome.
But if anyone tests out any bugs, please let me know. Let’s make it perfect.