Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

ruby on rails - Shorten long numbers to include K/M/B/T

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Put in your config/locales/en.yml:

en:
  number:
    human:
      decimal_units:
        format: "%n%u"
        units:
          unit: ""
          thousand: K
          million: M
          billion: B
          trillion: T
          quadrillion: Q

Then you'll get:

number_to_human 420 # => "420"
number_to_human 5680 # => "5.68K"
number_to_human 12680 # => "12.7K"
number_to_human 6802251 # => "6.8M"
number_to_human 894100158 # => "894M"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...