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?

user59388
  • 159
  • 1
  • 10

2 Answers2

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/

pawel
  • 35,827
  • 7
  • 56
  • 53
  • 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 Sep 16 '15 at 12:54
  • @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. – pawel Sep 16 '15 at 12:58
0

Try one of these two links :

http://www.w3schools.com/jsref/jsref_round.asp

Round to at most 2 decimal places (only if necessary)

Community
  • 1
  • 1
sms
  • 426
  • 1
  • 8
  • 23