I need to format a number to always have 3 digits so numbers should look like this
format(0) -> 0.00
format(1.3456) -> 1.34
format(12) -> 12.0
format(529.96) -> 529
format(12385.123) -> 12.3K
The numbers should also be rounded down, I'm having trouble coming up with an efficient way of doing all this, any help?
asked Sep 16, 2015 at 11:40
2 Answers 2
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/
answered Sep 16, 2015 at 12:09
2 Comments
user59388
Thanks! Though the demo here formats differently then the jsfiddle demo, here it formats 0.009 as 0.01, but correctly as 0.00 on the jsfiddle one
pawel
@user59388 yes there's a difference when using
Math.floor( num * 1000)/1000
which is prone to floating point math errors, and the string method used on jsfiddle.Try one of these two links :
answered Sep 16, 2015 at 11:44
1 Comment
user59388
Neither of them addresses formatting with 3 digits using float
Explore related questions
See similar questions with these tags.
lang-js