Floor function

Hey guys, trying to write a program using the floor function that outputs a whole integer, rounded to the tenths, rounded to the hundredths, and finally rounded to the thousandths. This in the code I have currently, but its outputting the hundredths and thousands the same, almost like the floor function isn't even working. Any suggestions?

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <math.h>
#include <iomanip>

using namespace std;

int roundToInteger(double);
double roundToTenths(double);
double roundToHundredths(double);
double roundToThousandths(double);
double number;

int main()
{
	cout << "Please end the number the you wish to round (-1 to quit): ";
	cin >> number;

	while (number != -1)

	{
		cout << roundToInteger(number) << endl;
		cout << roundToTenths(number) << endl;
		cout << roundToHundredths(number) << endl;
		cout << roundToThousandths(number) << endl;

		cout << "Please enter the number that you wish to round (-1 to quit): ";
		cin >> number;
	}

	return 0;
}
  
	int roundToInteger(double number)
	{
		return floor(number + .5);
	}

	double roundToTenths(double number)
	{
		return floor(number *10 + .5) / 10;
	}

	double roundToHundredths(double number)
	{
		return floor(number * 100 + .5) / 100;
	}
	
	double roundToThousandths(double number)
	{
		return floor(number * 1000 + .5) / 1000;
	}
	
Are you sure you had sufficient digits? When I tried it with 1.12345678, I got exactly the output I would expect. So I think maybe you should check your input or rebuild your program, as this source code seems correct.
Hello my2jlw3s,

I think you need to check out http://www.cplusplus.com/reference/cmath/floor/ and understand how floor works. Because what you are expecting and what you are doing in your functions are two different things.

This is a list of all that is in the cmath file http://www.cplusplus.com/reference/cmath/

Hope that helps,

Andy
Hello my2jlw3s,

During my dinner break I realized that rounding to the tenths, hundredths and thousandths place will not work with the floor function. Check out these links to work with the right side of the decimal:

http://www.cplusplus.com/reference/iomanip/?kw=iomanip

http://www.cplusplus.com/reference/ios/fixed/?kw=fixed

After that if you need help let us know.

Hope that helps,

Andy
Topic archived. No new replies allowed.