我想将逗号插入大整数进行打印。
julia> println(123456789) # Some kind of flag/feature inserts commas.
"123,456,789"
在Python 3.6+中,这很容易做到:
>>> print(f"{123456789:,d}")
123,456,789
但是,目前标准的Julia print / println功能似乎没有此功能。仅使用print / println函数我该怎么办?
我想在某些语言中最直接的方法是在'
中使用printf
格式修饰符。我朱莉娅这样看起来像这样:
using Printf # a stdlib that ships with julia which defines @printf
@printf "%'d" 12345678
但是,遗憾的是,此标志尚不支持,因为您可以从错误中看到:
julia> @printf "%'d" 12345678
ERROR: LoadError: printf format flag ' not yet supported
如果你喜欢这个功能,也许你应该考虑将它添加到Printf stdlib中,这样每个人都可以从中受益。我不知道这会有多困难。
更新:请注意,尽管宏是在stdlib Printf中定义的,但上面的错误在Base/printf.jl:48
中显式抛出。我还提出了问题here
这是一个基于正则表达式食谱的正则表达式的函数,由Goyvaerts和Levithan,O'Reilly,2nd Ed,p。 402,将逗号插入到返回字符串的整数中。
function commas(num::Integer)
str = string(num)
return replace(str, r"(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))" => ",")
end
println(commas(123456789))
println(commas(123))
println(commas(123456789123456789123456789123456789))
""" Output
123,456,789
123
123,456,789,123,456,789,123,456,789,123,456,789
"""