2

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
0

2 Answers 2

3

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

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
@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.
0
answered Sep 16, 2015 at 11:44

1 Comment

Neither of them addresses formatting with 3 digits using float

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.