Question

It's been quite a while since I last used D Programming Language, and now I'm using it for some project that involves scientific calculations.

I have a bunch of floating point data, but when I print them using writefln, I get results like: 4.62593E-172 which is a zero! How do I use string formatting % stuff to print such things as 0?

Right now I'm using a hack:

    if( abs(a) < 0.0000001 )
        writefln(0);
    else
        writefln(a);

it does the job, but I want to do it using the formatting operations, if possible.

UPDATE

someone suggested writefln("%.3f", a) but the problem with it is that it prints needless extra zeros, i.e. 0 becomes 0.000 and 1.2 becomes 1.200
Can I make it also remove the trailing zeros?

Was it helpful?

Solution

Short answer: This can't be done with printf format specifiers.

Since D uses the same formatting as C99's vsprintf(), you find your answer in this thread: Avoid trailing zeroes in printf()

OTHER TIPS

Try something like

writefln("%.3f", a);

Federico's answer should work, for more information check the format specifiers section.

I see you are currently using Phobos, however what you are trying to do is supported in Tango.

Stdout.formatln("{:f2}", 1.2);

will print "1.20"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top