Comment #0 by bearophile_hugs — 2013-04-28T08:16:20Z
The underscores allowed in number literals are quite handy to improve their readability (and this avoids some bugs in D code), so maybe it's worth having a standard simple way to also print numbers with them (one every three digits before the dot), to improve the output readability:
format("%_d", 1000000)
writefln("%_d", 1000000)
Expected output:
1_000_000
That notation is not flexible on purpose, so you can't use it to generate a string like:
1'000'000
Note: currently to!int("1_000") gives an error, so you can't round-trip like this:
format("%_d", 1000).to!int
Comment #1 by hsteoh — 2014-08-28T22:55:52Z
How would std.format know how many digits each to insert an underscore? In English notation, we generally group digits in 3's, but in other locales, other groupings are used (e.g., grouping digits by 4's).
Comment #2 by bearophile_hugs — 2014-08-29T06:56:32Z
(In reply to hsteoh from comment #1)
> How would std.format know how many digits each to insert an underscore? In
> English notation, we generally group digits in 3's, but in other locales,
> other groupings are used (e.g., grouping digits by 4's).
One possible solution is to also ask for the group size in the formatting string:
format("%3_d", 1000000) => 1_000_000
format("%4_x", 0xa5b71a) => 0xa5_b71a
Another solution is to keep this functionality out of format/write and add a function (perhaps a callable struct with a toString method that accepts a delegate) to Phobos that does just the grouping:
format("%s", withSeparators(1000000, 3, '_')) => 1_000_000
Where 3 and '_' are the defaults for the second and third argument.