www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Specifying precision in %(...%) print format

reply "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
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
Oct 14 2012
parent =?UTF-8?B?QWxpIMOHZWhyZWxp?= <acehreli yahoo.com> writes:
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
Oct 14 2012