Precision, new prices

downs default_357-line at yahoo.de
Sat Jul 25 05:12:57 PDT 2009


Saaa wrote:
> I thought my previous precision question was so retarded it didn't need any
> explanation; anybody here could easily tell me my fault in reasoning.
>
> Here is my question again but this time with examples.
>
> Is there some formatting which lets me print out a floating point in full
> precision?
>

Here's an incredibly simple hack.

import std.stdio, std.string;

string ftoaFull(float f) {
  if (f < 0) return "-" ~ ftoaFull(-f);
  auto start = f;
  auto res = toString(cast(int) f) ~ ".";
  while (true) {
    f -= cast(int) f;
    f *= 10;
    res ~= "0123456789"[cast(int) f];
    // The critical step
    if (cast(float) res.atof() == start) return res;
  }
}

void main() {
  writefln(ftoaFull(0f));
  writefln(ftoaFull(-5.234));
  writefln(ftoaFull(1f / 3f)); // problematic
}

Output:

0.0
-5.234
0.33333334

And there you have it.


More information about the Digitalmars-d-learn mailing list