[ruby-core:93869] [Ruby master Feature#16011] Digit grouping

From: shannonskipper@...
Date: 2019-07-22 18:01:07 UTC
List: ruby-core #93869
Issue #16011 has been updated by shan (Shannon Skipper).


``` ruby
class Integer
  def delimited(by: ',', digits: 0, padding: '0', every: 3)
    extra_padding_size = digits.to_int - Math.log10(self).floor.succ
    extra_padding = if extra_padding_size.positive?
      Array.new(extra_padding_size, padding.to_str.chr) 
    end

    (self.digits + extra_padding.to_a).each_slice(every).map do |triplet|
      triplet.reverse.join
    end.reverse.join(by.to_str)
  end
end

N = 4_200_000

N.delimited
#=> "4,200,000"

N.delimited(by: '_')
#=> "4_200_000"

N.delimited(every: 2, by: '_')
#=> "4_20_00_00"

N.delimited(digits: 12)
#=> "000,004,200,000"

N.delimited(digits: 12, padding: 'X')
#=> "XXX,XX4,200,000"
```



----------------------------------------
Feature #16011: Digit grouping
https://bugs.ruby-lang.org/issues/16011#change-79804

* Author: svnpenn (Steven Penny)
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
Ruby seems to have no way to format a number with grouped thousands. I see Rails
has an option:

    require 'active_support/all'
    1234.to_s(:delimited)

However in this case it seems that grouping cannot be combined with say, leading
zeros:

https://github.com/rails/rails/issues/36707

This is quite simple with other languages, for example JavaScript:

    (1234).toLocaleString(0, {minimumIntegerDigits: 7});
    "0,001,234"

Python:

    >>> format(1234, '08,')
    '0,001,234'

Go:

    package main
    import "golang.org/x/text/language"
    import "golang.org/x/text/message"
    func main() {
       message.NewPrinter(language.English).Printf("%07d\n", 1234)
       // 0,001,234
    }



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request@ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>

In This Thread

Prev Next