View mode: basic / threaded / horizontal-split · Log in · Help
October 15, 2012
Specifying precision in %(...%) print format
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

-- 
Trying to define yourself is like trying to bite your own teeth. -- Alan Watts
October 15, 2012
Re: Specifying precision in %(...%) print format
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
Top | Discussion index | About this forum | D home