In Python, we have something like print(f'{int(input()):,}')
that separates numbers by commas. That is for example, if we provide the input of 70671891032
we get 70,671,891,032
. Is there anything similar to this in Ruby (without the use of regex
)?
Asked
Active
Viewed 82 times
1
-
In Rails / active support, there is a method `number_with_delimiter` (see https://stackoverflow.com/a/1078366/2981429) but I'm not sure there's one in plain Ruby. – max pleaner Feb 05 '21 at 07:52
-
If you're not using Rails you can load the method from the `activesupport` gem: https://api.rubyonrails.org/classes/ActiveSupport/NumberHelper.html#method-i-number_to_delimited ... this gem contains a ton of useful core extensions – max pleaner Feb 05 '21 at 07:54
-
ActiveSupport uses regex, so, I could infere that Ruby doesn't have what you are looking for. https://github.com/rails/rails/blob/main/activesupport/lib/active_support/number_helper/number_to_delimited_converter.rb – iGian Feb 05 '21 at 07:57
2 Answers
1
Ruby's built-in string formatting doesn't have an option for a thousands separator.
If you don't want to use regular expressions, you could insert
a separator every 3 characters from the right, e.g. via step
:
input = 70671891032
string = input.to_s
(string.size - 3).step(1, -3) do |i|
string.insert(i, ',')
end
string
#=> "70,671,891,032"

Stefan
- 109,145
- 14
- 143
- 218
-
Does this really make sense? After all, the separator depends on the locale and is not necessarily a `,`. This point is also a bit unclear from the OPs question: Does he **always** wants to use a comma, or did he give this just as an example. – user1934428 Feb 05 '21 at 09:49
0
I expect this is not what you were looking for, but it does convert a non-negative integer to a string of digits with thousands separators.
def commafy(n)
s = ''
loop do
break s if n.zero?
n, n3 = n.divmod(1000)
s[0,0] = (n.zero? ? ("%d" % n3) : (",%03d" % n3))
end
end
input = 70671891032
commafy(input)
#=> "70,671,891,032"

Cary Swoveland
- 106,649
- 6
- 63
- 100