Ruby 相当于 Python 的传统数字分隔



在Python中,我们有类似print(f'{int(input()):,}')的东西,它用逗号分隔数字。例如,如果我们提供70671891032的输入,我们得到70,671,891,032。在Ruby中有类似的东西吗(不使用regex)?

Ruby的内置字符串格式没有千位分隔符选项。

如果你不想使用正则表达式,你可以从右边每隔3个字符insert一个分隔符,例如通过step:

input = 70671891032
string = input.to_s
(string.size - 3).step(1, -3) do |i|
string.insert(i, ',')
end
string
#=> "70,671,891,032"

我希望这不是您想要的,但它确实将非负整数转换为带有数千个分隔符的数字字符串。

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"

最新更新