Replacement for snprintf

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Nov 6 17:28:58 UTC 2019


On Wed, Nov 06, 2019 at 04:17:32PM +0000, Petar via Digitalmars-d wrote:
> On Wednesday, 6 November 2019 at 13:25:38 UTC, berni44 wrote:
[...]
> > b) How to query the current locale from D? Actually I only need the
> > number-separator in the current locale as a dchar. I found
> > core.stdc.locale but do not know how to use it.
> 
> I think the best way to go is to make it locale-independent and simply
> provide a way for user to specify the decimal separator (and other
> related locale details, if any).

Yes, I think in the long run this will be the more viable approach.
Depending on locale as a global state is problematic because it forces
formatting to be impure, and also forces users to implement hacks when
they need to temporarily change the locale. E.g., in a system like
snprintf, if you need to format German text with snippets of English
quotations, you will have to temporarily override LC_* somehow in order
to print a number with two different separators, or hack it with string
postprocessing, etc..

It's better to let the user pass in the desired separator as a parameter
-- the ',' flag in std.format already does this via the optional '?'
modifier, for example:

	writefln("%,?d", '_', 12345678); // 12_345_678
	writefln("%,?d", '|', 12345678); // 12|345|678

Conceivably one could extend the '.' flag with a '?' modifier as well,
so something like this:

	writefln("%.2?d", ',', 3.141592); // 3,14
	writefln("%.2?d", '_', 3.141592); // 3_14
	writefln("%.2?d", ':', 3.141592); // 3:14

Then programs that want to support locales can just do this:

	writefln("%.2?d", curLocale.separator, 3.141592);


T

-- 
I don't trust computers, I've spent too long programming to think that they can get anything right. -- James Miller


More information about the Digitalmars-d mailing list