tags:

views:

219

answers:

4

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?

+2  A: 

Try something like

writefln("%.3f", a);
Federico Ramponi
this prints 1 as 1.000 and 0 as 0.000, can i make it remove trailing zeros?
hasen j
Hmmm, I don't think so. Standard (C, D, whatever) format specifiers for floating point numbers come in the form %x.yf, where x is the width of the number being displayed, and y is the precision beyond the decimal point.
Federico Ramponi
Not with writefln/printf, anyway. Did you try D's streams?
Federico Ramponi
+1  A: 

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

CMS
+5  A: 

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()

Sascha
A: 

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"

larsivi