Floating point to string

Derek Parnell derek at nomail.afraid.org
Wed Jul 18 21:42:05 PDT 2007


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>

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
19/07/2007 2:41:16 PM


More information about the Digitalmars-d-learn mailing list