float CT stringification

Chris Wright dhasenan at gmail.com
Thu Jun 5 07:28:44 PDT 2008


Jarrett Billingsley wrote:
> const f = 1.2345;
> pragma(msg, f.stringof);

Or if the float is a value in a CTFE function, and you know your value 
is in a certain range, you could use fixed precision rather more easily:

/// Returns string representation of a decimal value.
char[] toString (real r, uint decimals = 2)
{
	int top = cast(long) r;
	int bottom = cast(ulong) (r - top);
	for (int i = 0; i < decimals; i++) bottom *= 10;
	return toString (top) ~ "." ~ toString (bottom, decimals);
}

/// Returns string representation of an integer value, with
/// leading zeros to pad out to length.
char[] toString (ulong value, uint length)
{
	char[] str = toString (value);
	while (str.length < length) str = "0" ~ str;
	return str;
}


More information about the Digitalmars-d-learn mailing list