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
 
         
                                         
                                         
                                         
                                        ![Interactive visualization of a graph in python [closed]](https://www.devze.com/res/2023/04-10/09/92d32fe8c0d22fb96bd6f6e8b7d1f457.gif) 
                                         
                                         
                                         
                                         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论