In Julia, Insert Commas Into Integers For Printing Like Python 3.6+
I want to insert commas into large integers for printing. julia> println(123456789) # Some kind of flag/feature inserts commas. '123,456,789' In Python 3.6+ this is easy to do
Solution 1:
I guess the most straightforward way in some languages would be to use the '
format modifier in printf
. I Julia this WOULD look like so:
using Printf # a stdlib that ships with julia which defines @printf@printf"%'d"12345678
However, unfortunately, this flag is not yet supported as you can see from the error you'll get:
julia> @printf "%'d"12345678
ERROR: LoadError: printfformat flag ' not yet supported
If you like this feature, maybe you should think about adding it to the Printf stdlib so that everyone would benefit from it. I don't know how difficult this would be though.
UPDATE: Note that although the macro is defined in stdlib Printf, the error above is explicitly thrown in Base/printf.jl:48
. I also filed an issue here
Solution 2:
Here is a function based on a Regex from "Regular Expressions Cookbook," by Goyvaerts and Levithan, O'Reilly, 2nd Ed, p. 402, that inserts commas into integers returning a string.
functioncommas(num::Integer)
str = string(num)
returnreplace(str, r"(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))" => ",")
endprintln(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
"""
Post a Comment for "In Julia, Insert Commas Into Integers For Printing Like Python 3.6+"