For numbers 0 - 1000:
function format( num ){
return ( Math.floor(num * 1000)/1000 ) // slice decimal digits after the 2nd one
.toFixed(2) // format with two decimal places
.substr(0,4) // get the leading four characters
.replace(/\.$/,''); // remove trailing decimal place separator
}
// > format(0)
// "0.00"
// > format(1.3456)
// "1.34"
// > format(12)
// "12.0"
// > format(529.96)
// "529"
Now for numbers 1000 - 999 999 you need to divide them by a 1000 and append "K"
function format( num ){
var postfix = '';
if( num > 999 ){
postfix = "K";
num = Math.floor(num / 1000);
}
return ( Math.floor(num * 1000)/1000 )
.toFixed(2)
.substr(0,4)
.replace(/\.$/,'') + postfix;
}
// results are the same for 0-999, then for >999:
// > format(12385.123)
// "12.3K"
// > format(1001)
// "1.00K"
// > format(809888)
// "809K"
If you need to format 1 000 000 as 1.00M then you can add another condition with "M" postfix etc.
Edit: demo up to Trillions: http://jsfiddle.net/hvh0w9yp/1/