Format double in decimal notation without trailing zeros after the decimal point

Steven Schveighoffer via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Mar 27 10:08:07 PDT 2015


On 3/27/15 11:02 AM, akaDemik wrote:
> The task seemed very simple. But I'm stuck.
> I want to:
>    1234567890123.0 to "1234567890123"
>    1.23 to "1.23"
>    1.234567 to "1.2346".
> With format string "%.4f" i get "1.2300" for 1.23.
> With "%g" i get "1.23456789e+12" for "1234567890123.0".
> I can not believe that it is not implemented. What did I miss?

I think you are asking for trouble to do this. Floating point is not 
exact, so for example, if I do

writefln("%.15f", 123456.789123);

I get:

123456.789122999995016

How far do you want to go before you determine there will only be zeros? 
It could be infinity.

I'd say your best bet is to format to the max level you want, e.g. "%.6f"

Then trim off any trailing zeros (and decimal point if necessary) after 
conversion to a string.

-Steve


More information about the Digitalmars-d-learn mailing list