Floating point to string
Joe
Joe_member at pathlink.com
Wed Jul 18 21:51:35 PDT 2007
Derek Parnell wrote:
> On Wed, 18 Jul 2007 21:28:47 -0500, Joe wrote:
>
>> How to do get a full string representation of a floating point?
>>
>> I've tried toString() on a floating point and the default precision for
>> numbers after the decimal point is 6. I've also tried using format
>> strings, but I can't seem to get a full textual representation of a
>> floating point. Is there some trick I'm missing?
>
> Try this ...
> <dcode>
> import std.stdio;
> import std.string;
>
> string FullTextValue(T)(T x)
> {
> string s;
>
> static if(is (T:long))
> const fmt = "%-52d";
> else
> static if(is (T:real))
> const fmt = "%52.52f";
> else
> const fmt = "%-s";
>
> s = std.string.format( fmt, x);
> for (int i = s.length-1; i >= 0; i--)
> {
> if (s[i] == '.')
> {
> s.length = i+2;
> break;
> }
> if ((s[i] != '0' && s[i] != ' ') || (i == 0))
> {
> s.length = i+1;
> break;
> }
> }
> return s;
> }
> void main()
> {
> real x;
> double y;
> float z;
> long a;
>
> x = 12345678901234567890.1234567890123456789;
> y = x;
> z = x;
> a = cast(typeof(a))x;
>
> writefln("real '%s'", FullTextValue(x));
> writefln("double '%s'", FullTextValue(y));
> writefln("float '%s'", FullTextValue(z));
> writefln("long '%s'", FullTextValue(a));
>
> x = 0.1234567890123456789;
> y = x;
> z = x;
> a = cast(typeof(a))x;
>
> writefln("real '%s'", FullTextValue(x));
> writefln("double '%s'", FullTextValue(y));
> writefln("float '%s'", FullTextValue(z));
> writefln("long '%s'", FullTextValue(a));
>
> }
> </dcode>
>
Thanks.
Out of curiosity (note: I haven't run this example yet), is 52 a magic
number for the floating point types in D? Is there a way at runtime to
get at the number of digits available after the decimal point depending
on whether it's a float, double or real?
More information about the Digitalmars-d-learn
mailing list