In C++ how do I get rid of trailing zeros without changing precision?

If I have setprecision(2) and output 12.65, 7.42, 2.82, 21.45, 6.40, 12.82 it displays the same numbers. But how can I change the 6.40 to display as 6.4 without changing it and also without changing the precision or resetting the flags?

3 Answers

  • Anonymous
    4 weeks ago


  • 1 month ago

    What's causing those trailing zeroes in this case is use of "fixed".  In that mode, formatted double and float values will have exactly the number of decimal places specified by setprecision.  That's by definition, so you can't change that without either not using fixed in the first place, or undoing it.

    In the default mode, with no "fixed" in effect, the precision setting specifies the maximum number of significant digits to display, so there's no easy way to limit the number of decimal places to 2.

    If you want a mode where the precision specifies the maximum number of places after then decimal point, and suppresses trailing zeroes, that mode doesn't exist in the C++ standard library. 

    Probably your best bet is to round the value to  the nearest multiple of 0.01 before outputting in non-fixed mode:

    double round2(double x)


        return std::floor(x*100.0 + 0.5) / 100.0;


    Then see what std::cout << round2(1.2345) << " " << round2(1234.5) do.

    Warning: If you want to display numbers 10,000 and larger, you'll need a larger precision setting than the default value of 6.

  • EddieJ
    Lv 7
    1 month ago

    Maybe you want to use the printf () function.

Still have questions? Get answers by asking now.