在ruby / rails中将1200转换为1.2K

时间:2023-01-27 12:31:39

I think there is a method within ruby or rails that does this but I can't remember where to find it or how to search for it, so I was hoping *'s collective wisdom might help. I don't mind writing a method to do this, but I'm sure someone has a better solution.

我认为在ruby或rails中有一个方法可以做到这一点,但我不记得在哪里找到它或如何搜索它,所以我希望*的集体智慧可能有所帮助。我不介意写一个方法来做到这一点,但我相信有人有更好的解决方案。

3 个解决方案

#1


29  

number_to_human(1200, :format => '%n%u', :units => { :thousand => 'K' })

# 1200 => 1.2K

#2


6  

If your number happens to be 1223 the accepted answer output would be 1.22K, include the precision parameter to reduce this to 1.2K. Also, if your number could be a wide range of numbers in the millions and billions, then best to cater for these also:

如果您的数字恰好是1223,则接受的答案输出将为1.22K,包括精度参数以将其减少到1.2K。此外,如果您的电话号码可能是数百万甚至数十亿的广泛数字,那么最好也可以满足这些要求:

number_to_human(1200, :format => '%n%u', :precision => 2, :units => { :thousand => 'K', :million => 'M', :billion => 'B' })
# => "1.2K"

number_to_human(1223, :format => '%n%u', :precision => 2, :units => { :thousand => 'K', :million => 'M', :billion => 'B' })
# => "1.2K" 

number_to_human(1223456789, :format => '%n%u', :precision => 2, :units => { :thousand => 'K', :million => 'M', :billion => 'B' })
# => "1.2B" 

#3


4  

Take a look at Rails Number Helper, the method number_to_human_size might be what you need.

看看Rails Number Helper,方法number_to_human_size可能就是你需要的。

#1


29  

number_to_human(1200, :format => '%n%u', :units => { :thousand => 'K' })

# 1200 => 1.2K

#2


6  

If your number happens to be 1223 the accepted answer output would be 1.22K, include the precision parameter to reduce this to 1.2K. Also, if your number could be a wide range of numbers in the millions and billions, then best to cater for these also:

如果您的数字恰好是1223,则接受的答案输出将为1.22K,包括精度参数以将其减少到1.2K。此外,如果您的电话号码可能是数百万甚至数十亿的广泛数字,那么最好也可以满足这些要求:

number_to_human(1200, :format => '%n%u', :precision => 2, :units => { :thousand => 'K', :million => 'M', :billion => 'B' })
# => "1.2K"

number_to_human(1223, :format => '%n%u', :precision => 2, :units => { :thousand => 'K', :million => 'M', :billion => 'B' })
# => "1.2K" 

number_to_human(1223456789, :format => '%n%u', :precision => 2, :units => { :thousand => 'K', :million => 'M', :billion => 'B' })
# => "1.2B" 

#3


4  

Take a look at Rails Number Helper, the method number_to_human_size might be what you need.

看看Rails Number Helper,方法number_to_human_size可能就是你需要的。