rounding of double

Hi,

I have a double with long decimal values eg : double x =32.1347896
I wanted to round it to 32.140000000
I tried using ceil (x*100)/100 but it returns 32.1399999
Please help
Floating point values are not good at storing exact values. You easily get rounding errors like this. You should consider storing the value without rounding it, and instead limit the number of decimals when you output the value.

1
2
3
4
5
6
7
8
#include <iostream>
#include <iomanip>

int main()
{
	double x = 32.1347896;
	std::cout << std::fixed << std::setprecision(2) << x; // Prints "32.13"
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
#include <cstdlib>

namespace JLBorges
{
    unsigned long long ipow10(unsigned int p) 
    {return (p == 0) ? 1 : 10 * ipow10(p - 1); }

    double round_d(double d, std::streamsize round_prec = 1, bool upDown = true)
    {
        double powval = ipow10(round_prec);

        if(upDown)
        return std::ceil(d * powval) / powval;
        return std::floor(d * powval) / powval;
    }
};

int main()
{
	double x = 32.1347896;

	std::cout.setf(std::ios::fixed);
	std::cout.precision(7);

	std::cout << "Before : " << x << std::endl;

	x = JLBorges::round_d(x, 2);

	std::cout << "After : " << x << std::endl;

 	return 0;
}


Before : 32.1347896
After : 32.1400000


Krulcifer Einfolk
Topic archived. No new replies allowed.