I've done numerous attempts to get this to work. But everything i've found so has ended up in either wrong rounding of the numbers - or hits a wall with the abbreviated character.
What i want is a function which i can give a single number, say like 1234
, and it should shorten it to: 1.23k
. But the precision can vary depending on how big the number is.
So my question is, how do i write such a function?
expected outcomes:
1 -> 1
9 -> 9
10 -> 10
100 -> 100
999 -> 999
1000 -> 1k
1001 -> 1k
1010 -> 1.01k
10100 -> 10.1k
1000000 -> 1m
1010000 -> 1.01m
10000000 -> 10m
1000000000000000 -> 1quad
1000000000000000000 -> 1quint
So the suffix is not alway single letters, they can be whole words.
Is this possible to do dynamically? or do i have to hardcode every single outcome?
Based on the information you gave, I came up with this solution. It is based on the Number.prototype.toExponential
method.
Example:
console.log(abbreviate(1000000000000000000)); // 1quint
You will have to tweak it though, so that it matches your need concerning rounding.