javascript convert number from thousands to k and millions to m

Solutions on MaxInterview for javascript convert number from thousands to k and millions to m by the best coders in the world

showing results for - "javascript convert number from thousands to k and millions to m"
Samantha
16 Jan 2017
1// converts number to string representation with K and M.
2// toFixed(d) returns a string that has exactly 'd' digits
3// after the decimal place, rounding if necessary.
4function numFormatter(num) {
5    if(num > 999 && num < 1000000){
6        return (num/1000).toFixed(1) + 'K'; // convert to K for number from > 1000 < 1 million 
7    }else if(num > 1000000){
8        return (num/1000000).toFixed(1) + 'M'; // convert to M for number from > 1 million 
9    }else if(num < 900){
10        return num; // if value < 1000, nothing to do
11    }
12}