Julia Learner
Julia Learner

Reputation: 2902

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:

>>> print(f"{123456789:,d}")
123,456,789

However, it does not appear that the standard Julia print/println functions have this feature at the present time. What can I do using just the print/println functions?

Upvotes: 2

Views: 1155

Answers (2)

carstenbauer
carstenbauer

Reputation: 10127

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: printf format 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

Upvotes: 3

Julia Learner
Julia Learner

Reputation: 2902

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.

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
"""

Upvotes: 2

Related Questions