Specifying precision in %(...%) print format

Ali Çehreli acehreli at yahoo.com
Sun Oct 14 22:48:59 PDT 2012


On 10/14/2012 10:43 PM, H. S. Teoh wrote:
> I have an array of reals that I want to format with writefln, but the
> precision field needs to be passed in a variable. For a single real, it
> would be writefln("%.*f", precision, x); but when I try this:
>
> 	int precision = ...;
> 	real[] array = ...;
> 	writefln("%(%.*f, %)", precision, array);
>
> I get a runtime exception with the message "integral". I assume that's
> because %(%) is expecting an array, but sees an int, so it fails. But
> swapping the order of parameters doesn't help either:
>
> 	writefln("%(%.*f, %)", array, precision);
>
> produces "floating point format failure".
>
> What's the right way to do this?
>
>
> T
>

Here is a way with format:

import std.stdio;
import std.string;

void main()
{
     int precision = 2;
     real[] array = [ 1.234 ];
     writefln(format("%%(%%.%sf, %%)", precision), array);
}

Ali


More information about the Digitalmars-d-learn mailing list