Search code examples
c++floating-pointiostream

How do I remove trailing zeros when printing a floating-point number?


I want to ask how to remove trailing zeros after decimal point?

I've read lots of topics about it but I don't understand them clearly. Could you show me any easy understanding ways ?

For example 12.50 to 12.5, but the actual output is 12.50


Solution

  • This is one thing that IMHO is overly complicated in C++. Anyway, you need to specify the desired format by setting properties on the output stream. For convenience a number of manipulators are defined.

    In this case, you need to set fixed representation and set precision to 2 to obtain the rounding to 2 decimals after the point using the corresponding manipulators, see below (notice that setprecisioncauses rounding to the desired precision). The tricky part is then to remove trailing zeroes. As far as I know C++ does not support this out of the box, so you have to do some string manipulation.

    To be able to do this, we will first "print" the value to a string and then manipulate that string before printing it:

    #include <iostream>
    #include <iomanip>
    
    int main()
    { 
        double value = 12.498;
        // Print value to a string
        std::stringstream ss;
        ss << std::fixed << std::setprecision(2) << value;
        std::string str = ss.str();
        // Ensure that there is a decimal point somewhere (there should be)
        if(str.find('.') != std::string::npos)
        {
            // Remove trailing zeroes
            str = str.substr(0, str.find_last_not_of('0')+1);
            // If the decimal point is now the last character, remove that as well
            if(str.find('.') == str.size()-1)
            {
                str = str.substr(0, str.size()-1);
            }
        }
        std::cout << str << std::endl;
    }