Bug 10001 – string formatting with underscores

Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-04-28T08:16:20Z
Last change time
2018-01-05T13:28:23Z
Keywords
pull
Assigned to
No Owner
Creator
bearophile_hugs

Comments

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.
Comment #3 by hsteoh — 2017-03-23T20:02:44Z
Robert Schadek has submitted a pull for this: https://github.com/dlang/phobos/pull/5303
Comment #4 by github-bugzilla — 2017-04-19T18:38:58Z
Commit pushed to master at https://github.com/dlang/phobos https://github.com/dlang/phobos/commit/5de9af20ad07ebe485394309867073baa53b627b Merge pull request #5303 from burner/origin/formatunderscore fix Issue 10001 - std.format insert underscores into numbers merged-on-behalf-of: unknown
Comment #5 by github-bugzilla — 2017-06-17T11:34:34Z
Commit pushed to stable at https://github.com/dlang/phobos https://github.com/dlang/phobos/commit/5de9af20ad07ebe485394309867073baa53b627b Merge pull request #5303 from burner/origin/formatunderscore
Comment #6 by github-bugzilla — 2018-01-05T13:28:23Z
Commit pushed to dmd-cxx at https://github.com/dlang/phobos https://github.com/dlang/phobos/commit/5de9af20ad07ebe485394309867073baa53b627b Merge pull request #5303 from burner/origin/formatunderscore