Is there a direct way in Julia to format a number e.g. 9999999999 as a String object "9,999,999,999" for making it convenient to read?

Is there any Julia function or a straightforward way that can format a large integer number as a String object in which every 3 digits can become delimited by comma (,) from the end?

This thing we can do in Python using f-String. E.g.

>>> num = 9999999999

>>> num
9999999999

>>> f'{num:,}'
'9,999,999,999'

Can we do anything similar in Julia?

1 Like

I do not know a direct method, but a solution approach is given here. It uses a function

function commas(num::Integer)
    str = string(num)
    return replace(str, r"(?<=[0-9])(?=(?:[0-9]{3})+(?![0-9]))" => ",")
end

which yields

julia> commas(123456789)
"123,456,789"

2 Likes

Humanize.jl has a Humanize.digitsep(num) function for that.

7 Likes

There is Formatting.jl:

julia> using Formatting
julia> format(1_000_000, commas=true)
"1,000,000"

Or StringLiterals.jl through Strs.jl:

julia> using Strs
julia> f"\%'d(1_000_000)"
"1,000,000"

Or Format.jl:

julia> using Format
julia> cfmt("%\'d", 1_000_000)
"1,000,000"
11 Likes