Download Reference Manual
The Developer's Library for D
About Wiki Forums Source Search Contact

Layout format string for decimal places?

Moderators: larsivi kris

Posted: 08/23/09 06:05:10

Is there a Layout format string to adjust the number of decimal places to show on floating point types?

Author Message

Posted: 08/23/09 07:16:21

Such as the below?

Stdout.formatln("My float looks like {:f4}", 3.1457);

Posted: 08/23/09 07:53:11

Oh, from the docs it looked like putting a number after the type code referred to the number of digits before the decimal point. But I guess it depends on the type then. Mind if I update to include this "f"?

Also, does this mean that it's not possible to specify both the number of digits before AND the number of digits after the decimal point?

And is there a connection between that letter and the TypeCode? enum the Layout source uses? I'm guessing at this point that there isn't, but if there is then it would seem to indicate that "f" is for "float", so if I passed in a real or a double would it get downcast or something?

Posted: 08/23/09 08:30:49

There are several components to the format specifier, so you can have


where the first number is the index, the second how much space should be used minimum (if the formatted number is larger, it will use more than that minimum), and the stuff after the : is how to format, including number of decimals for floating point numbers.

There isn't any problem if you format doubles or real, they are just larger floating point values.

Feel free to update the documentation (tell me if you don't have access).

Posted: 10/05/09 05:59:03

Is there a way to force the "f" format to never switch to "e" format if there are not enough decimal places ?

In the following code I wanted to display numbers with the decimal point in the same column, but the small value generated from a rounding in a calculation throws the formatting out. Is there a way around this ?

my code:

    double	value=10.123;
    Stdout.formatln("{,6:f3} x", value);
    value = 0.00005;
    Stdout.formatln("{,6:f3} x", value);
    value = 0.432e-16;
    Stdout.formatln("{,6:f3} x", value);

produces the output:

10.123 x
 0.000 x
0.432e-16 x

I would like "0.000 x" as the third item instead of "0.432e-16 x".