How do I truncate double like 99.998765 to something like 99.99 instead of 100.00? If some printf("%.2f", myDouble); gives 100
That is not what I want.
Any help is appreciated

Recommended Answers

All 6 Replies

Nope,
I don't want it to be approximated, just truncated.
Instead of writing 2.156 as 2.16 I want it as 2.15

In that case you could use a custom function which truncates:

#include <iostream>
#include <string>
#include <sstream>

std::string truncate(double d, unsigned decimals)
{
    std::stringstream sstr;
    sstr << d;
    std::string d_str = sstr.str();
    return d_str.substr(0, d_str.find_first_of(".") + decimals + 1);
}

int main ()
{
    double d = 99.128;
    std::cout << truncate(d,2);
}

If you want the return-value to be of type "double", you can convert it back using a stringstream

commented: Cool Man, I was wondering and you gave a cane +4

Is it possible to use floor()?

Is it possible to use floor()?

Yes it is. But that would return 99 instead of 99.xx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.