Stop to! rounding?

H. S. Teoh hsteoh at quickfur.ath.cx
Wed Jul 3 11:59:53 PDT 2013


On Wed, Jul 03, 2013 at 07:56:28PM +0200, Marco Leise wrote:
> Am Tue, 2 Jul 2013 22:21:52 -0700
> schrieb "H. S. Teoh" <hsteoh at quickfur.ath.cx>:
> 
> > On Tue, Jul 02, 2013 at 10:14:33PM -0700, Ali Çehreli wrote:
> > [...]
> > > import std.stdio;
> > > import std.conv;
> > > 
> > > void main()
> > > {
> > >     auto a = to!double("151.42499");
> > >     writefln("%.60f", a);
> > > }
> > 
> > I wouldn't write it like that; IMO it's better to write:
> > 
> > 	writefln("%.*f", double.dig, a);
> > 
> > So that you don't give the wrong impression that there are more digits
> > than are actually there. Using double.dig also lets you see all the
> > digits that *are* there, not a rounded value, that the OP was
> > complaining about.
> > 
> > 
> > T
> > 
> 
> *f ? I didn't know that you can format the format string like
> that. Thanks for the tip.
[...]

Basically, it's a wildcard precision. Usually you'd write %.5f for 5
digits following the decimal point, for example, but that requires
hardcoding the integer literal into the format string. In some cases you
need it to be variable, so '*' was introduced as a stand-in for the next
item in the argument list. So writefln("%.*f", 5, a) is equivalent to
writefln("%.5f", a).

The wildcard * can also be used in the field-width, so writefln("%*.*f",
5, 2, 1) is equivalent to writefln("%5.2f", 1).

This isn't D's innovation, BTW, the * width/precision specifier is
defined in the same way in C's printf().


T

-- 
He who does not appreciate the beauty of language is not worthy to bemoan its flaws.


More information about the Digitalmars-d-learn mailing list