March 31, 2004
I'm starting to get into D coding in a serious way now. Anyhow, for what its worth, here is an alternate 'toString' for doubles. I didn't like the way the existing one hides some precision for some values.

Any constructive critisms welcome...

//-------------- toString -----------//
char[] toString(double x)
{
    char[] buffer;
    int l;
    int a;

    // Allocate a big-enough(tm) buffer
    buffer.length = 40;

    // Do the basic formatting into the buffer
    l = sprintf(buffer, "%015.10f", x);

    // Strip off leading zero chars except the one before the decimal.
    for(a=0; (a<l)  && (buffer[a] == '0'); a++){};
    if (buffer[a] == '.')
        a--;

    // Strip off trailing zero chars and any final decimal point if it trails.
    for(l--; (l>=0) && (buffer[l] == '0'); l--){};
    if (buffer[l] == '.')
        l--;

    // Return whatever's left.
    return buffer[a..l+1];
}


-- 
Derek
April 01, 2004
I don't know if it has come up before but yet another nice function to add to std.string's toString collection would be

char[] toString(Object obj)
{
  if (obj is null)
    return "null";
  else
    return obj.toString();
}

that way you don't have to check if obj is null before toString'ing it.

More directly related to the original post, how about overloading toString with formatting inputs like

char[] toString(double x, int precision)
{
// something like Derek's toString or maybe just
// sprintf("%.10g") where 10 is the precision
}

Also maybe it's worth tossing in
char[] toString(double x, char[] format)
{
  char[] buf = new char[40]; // be smarter here
  buf.length = sprintf(buf,format,x);
  return buf;
}

-Ben

On Wed, 31 Mar 2004 15:16:10 +1000, "Derek Parnell" <Derek.Parnell@psyc.ward> wrote:

>I'm starting to get into D coding in a serious way now. Anyhow, for what its worth, here is an alternate 'toString' for doubles. I didn't like the way the existing one hides some precision for some values.
>
>Any constructive critisms welcome...
>
>//-------------- toString -----------//
>char[] toString(double x)
>{
>     char[] buffer;
>     int l;
>     int a;
>
>     // Allocate a big-enough(tm) buffer
>     buffer.length = 40;
>
>     // Do the basic formatting into the buffer
>     l = sprintf(buffer, "%015.10f", x);
>
>     // Strip off leading zero chars except the one before the decimal.
>     for(a=0; (a<l)  && (buffer[a] == '0'); a++){};
>     if (buffer[a] == '.')
>         a--;
>
>     // Strip off trailing zero chars and any final decimal point if it
>trails.
>     for(l--; (l>=0) && (buffer[l] == '0'); l--){};
>     if (buffer[l] == '.')
>         l--;
>
>     // Return whatever's left.
>     return buffer[a..l+1];
>}