JSFiddle - React, Tailwind, and code Playground
JavaScript
function format( num ){
var postfixes = ['', 'K', 'M', 'B', 'T'], thousands = 0;
while( num > 999 ){
num = num / 1000;
thousands += 1;
}
return parseFloat(
num.toString()
.replace(/(\.\d{2}).*/,"$1")
)
.toFixed(2)
.substr(0,4)
.replace(/\.$/,'') + postfixes[ thousands ];
}
var tests = [ 0, 1.3456, 12, 529.96, 1001, 12385.123, 899999, 1000000, 2565898, 123456789, 1234567890 ];
tests.forEach( function( n ){
console.log( "%f formatted as %s", n, format(n) );
});