Remove all trailing zeros from a double while formatting in a string in C++

480 views Asked by At

I want to remove all the trailing zeros from a double number. I know I can use std::setprecision() to print it, but I want to modify the actual number to only make it two digits after the decimal.

class Circle {
    private:
        double r, PI = 3.14159;
    public:
        Circle(double r) {
        this->r = r;
    }
        double area() {
            return PI * r * r;
        }
    double circumference() {
        return 2 * PI * r;
    }
        double getRadius() {
            return r;
        }
        string toString() {
            string str;
            str += "Circle{radius=" + to_string((r)) + "}";

            return str;
        }
    };

From the twoString() function I want to return the radius till two decimal digits only, however, I am getting "Circle{radius=2.500000}" after I pass 2.5, similarly, for 4 I am getting "Circle{radius=4.000000}". I want it to be only 4 here.

2

There are 2 answers

2
MikeCAT On

Modifying original number won't work because data format for double should be defined in your platform (typically IEEE754 format).

std::stringstream should be helpful. It can be used like this:

string toString() {
    std::stringstream ss;
    ss << "Circle{radius=" << r << "}";

    return ss.str();
}
1
srv236 On

Or you can do :

rad = (r * 100) / 100;

and then instead of r use rad in your printing method. This will truncate it to 2 decimal places.

If you want to round, the use

rad = ceilf(r * 100) / 100;