Shorten long numbers to include K/M/B/T

Viewed 5702

I've checked out Rails number_to_human but it's not exactly what i want.

I'd like to shorten long numbers without including the full unit name:

420 -> 420
5,680 -> 5,680
12,680 -> 12.6K
6,802,251 -> 6.80M
894,100,158 -> 894M

As you see there is no specific precision but it's more about the length of the overall number

Any one has a good helper method for this?

2 Answers

Like this:

number_to_human(a_number,format:'%n%u',units:{thousand:'K',million:'M',billion:'B'})
Related