@printf with comma for thousands separator

1,790 views
Skip to first unread message

Arch Call

unread,
Nov 8, 2014, 6:05:08 AM11/8/14
to julia...@googlegroups.com
How would I use a @printf macro to use commas for thousands separators in integers?

@printf "%d \n" 12345678

This outputs:  12345678

I would like the output to be:   12,345,678

Thanks...Archie

Tony Fong

unread,
Nov 21, 2014, 3:48:35 AM11/21/14
to julia...@googlegroups.com
I just wrote a package that may do what you need in runtime.


It's not in METADATA yet, since I'm not sure if its implementation is kosher. (There's a trick of generating new generic functions at runtime within the module name space).

Speed is decent (within 30% of standard macro). You can run the test script to see the difference on your machine.

After you clone it, you can try

using NumFormat

format( 12345678, commas=true) # method 1. slowest, but easiest to change format in a readable way

sprintf1( "%'d, 12345678 ) # method 2. closest to @sprintf in form, so one can switch over quickly

f = generate_formatter( "%'d" ) # method 3. fastest if f is used repeatedly
f( 12345678 )

Tony

Arch Call

unread,
Nov 21, 2014, 8:18:08 AM11/21/14
to julia...@googlegroups.com
Thanks Tony for getting back.

I wrote a Julia function that: thousands separates, truncates on specified digits to right of decimal, and pads spaces for vertical alignment.

I'll reply to your post this weekend my source code.  Maybe you can lift various aspects of my function into your code.

Best regards...Archie

Tim Holy

unread,
Nov 21, 2014, 9:18:39 AM11/21/14
to julia...@googlegroups.com
Looks really nice. There are several packages that have been dipping into the
guts of Base.Grisu, this looks like a promising alternative.

--Tim

Tony Fong

unread,
Nov 21, 2014, 9:30:24 AM11/21/14
to julia...@googlegroups.com
I'm only aware of https://github.com/lindahua/Formatting.jl so I'd welcome pointers about the other packages, so we can pool efforts and ideas. 

Please note that my package only tries to focus on formatting 1 number at a time. It's easy to concatenate strings in Julia, so I didn't worry about replicating the full varargs functionalities of sprintf.

Tony Fong

unread,
Nov 21, 2014, 10:06:33 AM11/21/14
to julia...@googlegroups.com
Oh I see it now. https://github.com/dcjones/Showoff.jl It's a cool package!
Reply all
Reply to author
Forward
0 new messages