I need to show a currency value in the format of 1K
of equal to one thousand, or 1.1K
, 1.2K
, 1.9K
etc, if its not an even thousands, otherwise if under a thousand, display normal 500
, 100
, 250
etc, using JavaScript to format the number?
Advertisement
Answer
Sounds like this should work for you:
function kFormatter(num) { return Math.abs(num) > 999 ? Math.sign(num)*((Math.abs(num)/1000).toFixed(1)) + 'k' : Math.sign(num)*Math.abs(num) } console.log(kFormatter(1200)); // 1.2k console.log(kFormatter(-1200)); // -1.2k console.log(kFormatter(900)); // 900 console.log(kFormatter(-900)); // -900