Feature #16011
closedDigit grouping
Description
Ruby seems to have no way to format a number with grouped thousands. I see Rails
has an option:
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:
Python:
Go:
Updated by znz (Kazuhiro NISHIYAMA) almost 7 years ago
- Tracker changed from Bug to Feature
- Backport deleted (
2.5: UNKNOWN, 2.6: UNKNOWN)
Updated by duerst (Martin Dürst) almost 7 years ago
Just for the record:
- What to use as thousands separator is locale-dependent. It can be a comma (US), a dot (Germany), an apostrophe (Switzerland), a space (Sweden; usually a narrow-width, non-breaking space), and so on.
- Some locales don't use thousands separators, and the separators don't have to come in regular intervals (e.g. Hindi).
Updated by shyouhei (Shyouhei Urabe) almost 7 years ago
- Related to Feature #12447: Integer#digits for extracting digits of place-value notation in any base added
Updated by shyouhei (Shyouhei Urabe) almost 7 years ago
Updated by znz (Kazuhiro NISHIYAMA) almost 7 years ago
Updated by shyouhei (Shyouhei Urabe) almost 7 years ago
Updated by shevegen (Robert A. Heiler) almost 7 years ago
The python example seems quite concise to me:
I can not say how useful this may be though.
The method-names seem a bit strange to me - format() seems very generic
and delimited() is .... hmmm. I am not sure with what this is "de-limited".
Updated by shan (Shannon Skipper) almost 7 years ago
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"
Updated by Hanmac (Hans Mackowiak) almost 7 years ago
because it is locale-dependent as duerst said, i think it should only be part of an intl gem where you can control the locale
Updated by ko1 (Koichi Sasada) almost 7 years ago
- Status changed from Open to Assigned
- Assignee set to matz (Yukihiro Matsumoto)
Updated by matz (Yukihiro Matsumoto) almost 7 years ago
- Status changed from Assigned to Rejected
I agree with @duerst (Martin Dürst) and @Hanmac (Hans Mackowiak)
It's handy but it cannot be in the standard library.
Matz.
Updated by mame (Yusuke Endoh) over 4 years ago
- Related to Feature #18410: Proposal to make inspect include underscores on numerics added