Skip to content

Instantly share code, notes, and snippets.

@Phrogz
Created October 22, 2019 02:35
Show Gist options
  • Save Phrogz/ed8b394dd7600df23b6810f66610ac08 to your computer and use it in GitHub Desktop.
Save Phrogz/ed8b394dd7600df23b6810f66610ac08 to your computer and use it in GitHub Desktop.
Rounding to varying precision
n = [
[1,'1'],
[6,'6'],
[9,'9'],
[10,'10'],
[11,'11'],
[19,'19'],
[90,'90'],
[99,'99'],
[100,'100'],
[101,'101'],
[150,'150'],
[403,'403'],
[708,'708'],
[992,'992'],
[999,'999'],
[1000,'1.00k'],
[1001,'1.00k'],
[1472,'1.47k'],
[1920,'1.92k'],
[1999,'2.00k'],
[2000,'2.00k'],
[4032,'4.03k'],
[9813,'9.81k'],
[9999,'10.0k'],
[1e4, '10.0k'],
[10010,'10.0k'],
[60712,'60.7k'],
[98712,'98.7k'],
[99999,'100k'],
[1e5,'100k'],
[1e5+10,'100k'],
[4e5+10,'400k'],
[9e5,'900k'],
[999999,'1.00M'],
[1e6,'1.00M'],
[1234567,'1.23M'],
[12345678,'12.3M'],
[123456789,'123M'],
]
function siRound(x) {
if (x<1e3) return x+'';
let digits = Math.round(Math.log10(x)*100)/100 | 0
let tier = digits/3 | 0
let scale = 10**(tier*3)
return (x/scale).toFixed(2-digits%3) + (["","k","M","G"])[tier]
}
n.forEach( ([x,expected]) => console.log(x, expected, siRound(x)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment