0

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

3
Contributors
6
Replies
7
Views
7 Years
Discussion Span
Last Post by Stefano Mtangoo
0

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

1

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

Votes + Comments
Cool Man, I was wondering and you gave a cane
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.