开发者

Does Ruby have any number formatting classes?

Does Ruby have any Formatter classes or methods that can be used to format numbers for things like currency, etc., or are there any gems tha开发者_Python百科t do this, or do you have to write you own?


Ruby has all the standard print formatters, available either via printf, sprintf or using 'formatstring' % [var1, ...].

>> '%.2f' % 3.14159 #=> "3.14"
>> '%4s %-4s' % ['foo', 'bar'] #=> " foo bar "


Try this:

1234567890.123.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
=> "1,234,567,890.123"

Taken from a comment by @pguardiario in a similar thread


You can use Kernel#sprintf (or Kernel#format) and do it that way. API Link.


Ruby provides Kernel#format class method that looks more like the python 3.x method. Checkout Ruby's Docs for more details. This can be used to format both string and number.There are others like %e and %g for exponential and etc.

Below are some examples.

number use %f for float and %d for integer

format('%.2f', 2.0) #=> "2.00"

format('%.d', 2.0) #=> "2"

string use %s

format('%.4s', "hello") #=> "hell"

format('%6s', "hello") #=> " hello"

format('%-6s', "hello") #=> "hello "


You can check out the ruby on rails ActionView::Helpers::NumberHelper

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜