Rounding Decimals to whole numbers - c++

I was looking around and could not find exactly what I was looking for.
I want to round all my numbers up to the whole number.
Example:
5.9 would be 6
5.5 would be 6
5.1 would be 6
5.000001122 would be 6
5.0 would be 5
I was thinking if I put them into ints that would get rid of the decimal but it did not look right as the decimals were just dropping off. Am I correct here?
So I thought about just doing that then adding 1 to the final result which would fix about 99% of the problem but if my result is 5 I do not want to add 1 to it.
How would I go about fixing this issue I have?

You're looking for the ceil() function from <math.h> or std::ceil() from <cmath>.

[...] but it did not look right as the decimals were just dropping off. Am I correct here?
Correct, casting to an int simply discards the fractional part (i.e. rounds toward zero).
While std::ceil() from cmath will work for all the examples in your question, the question does not specify the required behaviour for negative values. For example should -5.9 round to -6.0 or -5.0? ceil(-5.9) = 5.0, which may not be what you want. If you want -6.0, then you would need floor(-5.9), so the code would have to be:
round = f > 0 ? std::ceil(f) : std::floor(f) ;
The question is whether you are rounding up as ceil() does, or rather rounding away from zero (up in magnitude rather than up in value) which the above code does?

Use math.h function ceil(number)

Related

I'm trying to round a float to two decimal points but it's incorrect. How to fix this rounding error in C++?

I'm having trouble with rounding floats. I'm solving a task where you need to round your result to two decimal points. But I can't do it when the third decimal point is 5 because it's stored incorrectly.
For example: My result is equal to 1.005 and that should be rounded to 1.01. But C++ rounds it to 1.00 because the original float is stored as 1.0049999... and not 1.005.
I've already tried always adding a very small float to the result but there are some other test cases which are then rounded up but should be rounded down.
I know how floating-point works and that it is often not completely accurate. I'm just wondering whether anyone has found a way around this specific problem.
When you say "my result is equal to 1.005", you are assuming some count of true decimal digits. This can be 1.005 (three digits of fractional part), 1.0050 (four digits), 1.005000, and so on.
So, you should first round, using some usual rounding, to that count of digits. It is simpler to do this in integers: for example, with 6 fractional digits, it means some usual round(), rint(), etc. after multiplication by 1,000,000. With this step, you are getting exact decimal number. After this, you are able to make the required final rounding to what you need.
In your example, this will round 1,004,999.99... to 1,005,000. Then, divide by 10000 and round again.
(Notice that there are suggestions to make this rounding in yet specific way. The General Decimal Arithmetic specification and IBM arithmetic manuals suggest this rounding is done in the way that exact fractional part 0.5 shall be rounded away from zero unless least significant result bit becomes 0 or 5, in that case it is rounded toward zero. But, if you have no such rounding available, a general away-from-zero is also suitable.)
If you are implementing arithmetic for money accounting, it is reasonable to avoid floating point at all and use fixed-point arithmetic (emulated with integers, if needed). This is better because you the methods I've described for rounding are inevitably containing conversion to integers (and back), so, it's cheaper to use such integers directly. You will get inexact operation checking as well (by cost of explicit integer overflow).
If you can use a library like boost with its Multiprecision support.
Another option would be to use a long double, maybe that's precise enough for you.

How make a good calculator with floating point arithmetic [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 4 years ago.
Here is how my calculator should work:
There is a JSON value where I can write the first multiplier - something like this:
{
"value1": 1.4
}
On the calculator I can write the second multiplier - only 10^n numbers (10, 100, ..., 10000000). And my calc should return me an integer, as I know that always people who use my calc with write less numbers after the decimal point for the first multiplier than we have 0s on the calc for the second multiplier. Yes, my calc is a very-very strange one.
Here are valid inputs:
v1=1.4; v2=100;
v1=1.414; v2=100000;
v1=1.1; v2=100;
What happens when I do this, for example for value1=1.4 and value2=10000 I get 13900. As far as float cannot hold any number sometimes it stores different numbers. For 1.4 internally it stores 1.399999 on my machine. I know why, but you know the QA engineer who tests my app tells me that I need to get 14000. Your calc does not work. How to make my calc so that I will print correct number?
P.S. Of course I have cut out my real problem from the context but the thing is that I have a float in a file and a 10^n number in my program as a user input. How to get correct result?
EDIT1: I don't ask why float works that way. I know why. I ask how to solve the problem even when float works that way.
EDIT2: I use RapidJson to read the JSON file which already returns me wrong number as a double precision number. I can't use libraries that provide with higher precision floating points.
Round the result when you format it for display. A double precision value is correct to about 15 significant digits, so if you round the result to 12 significant digits you're not going to surprise the user.

For with minor or equal condition in C++ [duplicate]

This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 5 years ago.
I am doing a loop to perform some calculations from t=0 to t=1 (included).
That should be easy like this:
for(double t = 0; t<=1; t = t + 0.05)
{
DEBUG_LOG1 (LVL1, t);
//DoMaths
}
But for some reason, t is being logged from 0 to 0.95, not including t=1, as it if was t<1 instead of t<=1.
Where is the problem in my code?
This is a simple problem with types. Because it is a floating point number will will likely never get precisely 0.05 or 1.00.
Rather you'll it will try for 0.05 but really will be something like 0.050000000000000012 which added together 20 times is not 1 but more like 1.00000000000000024 and will therefore not correspond with 1.
There is not problem with your code per se since you catch the problem by using <= instead of =.
You can read more about floating point numbers on http://www.learncpp.com/cpp-tutorial/25-floating-point-numbers/
I think it may be because 0.05 is not exactly representable as a floating point value. It is only approximate. Try running this program.
#include <stdio.h>
int main()
{
double x = 0.05;
printf("%.50lf\n", x);
return 0;
}
Here I tell printf to give me a lot of excess precision. This prints out the value
0.05000000000000000277555756156289135105907917022705.
Now if I take that value and multiply and add 0.5 to it 19 times in a loop I get...
1.00000000000000022204460492503130808472633361816406
See how it is not exactly 1 but slightly greater. This is the reason comparing equality between floats leads to strange results. You can get around this by adding a small epsilon to 1. For instance compare to 1.001 in your loop.
Decimal numbers can't be accurately represented using floating types. For example 0.05 can't be accurately represented in type double and depending on the platform it might be: 0.050000000000000003 or similar. So that tiny little bit always gets added in your loop. By the time you think it is 0.95 it is actually 0.95000000000000029 or similar and adding 0.05 makes it greater than 1, hence the observed results. More info on the subject in this SO post:
Is floating point math broken?

How to control double precision computing to avoid rounding errors in C++ linux x86_64?

In a C++ code on linux x86_64, I need to double precision computing (+ or -).
26.100000000000001 - 26 + 0.10000000000000001
I got:
0.20000000000000143
I want to get 0.2.
here, the display format is not import, the computing results will be used for some if-else branch conditions. So, I only want the if-else conditions compare the 4 digits after the decimal digit.
It seems a rounding error ?
How to restrict the computing precision to 4 digits after decimal point ?
I do not want to call any functions in order to avoid overhead.
I do not want to use stringstream due to transformation overhead.
Any better ideas ?
thanks
The computing precision is fine. It's the display precision you're trying to control. You can do that with setprecision() if using <iostream> or a formatter like "%.4f" if using <stdio.h>.
You are already calling functions since you are displaying the result as decimal!
P.S. 0.1 cannot be exactly represented by a float, double, or any binary-mantissa format. It factors into (1/2) * (1/5), and decimal 1/5 is an infinitely-repeating digit sequence in binary.
P.P.S. Go look at GMP. It might be your best hope.
If you just want to print it it, you can use printf("%10.4lf"). You can alter the precision to anything you want, of course.
If you are only interested in equality up to four decimal places, multiply everything by 10,000 and use integer arithmetic. (You might need to round after multiplying by 10,000.)

Incorrect floating point math?

Here is a problem that has had me completely baffled for the past few hours...
I have an equation hard coded in my program:
double s2;
s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42;
Every time i run the program, the computer spits out 3 as the answer, however doing the math by hand, i get 4. Even further, after inputting the equation into Matlab, I also get the answer 4. Whats going on here?
The only thing i can think of that is going wrong here would be round off error. However with a maximum of 5 rounding errors, coupled with using double precision math, my maximum error would be very very small so i doubt that is the problem.
Anyone able to offer any solutions?
Thanks in advance,
-Faken
You're not actually doing floating point math there, you're doing integer math, which will floor the results of divisions.
In C++, 5/4 = 1, not 1.25 - because 5 and 4 are both integers, so the result will be an integer, and thus the fractional part of the result is thrown away.
On the other hand, 5.0/4.0 will equal approx. 1.25 because at least one of 5.0 and 4.0 is a floating-point number so the result will also be floating point.
You're confusing integer division with floating point division. 3 is the correct answer with integer division. You'll get 4 if you convert those values to floating point numbers.
Some of this is being evaluated using integer arithmetic. Try adding a decimal place to your numbers, e.g. 6.0 instead 6 to tell the compiler that you don't want integer arithmetic.
s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42;
yields 3
s2 = -(0.*13.)/84.+6./42.-0./84.+24./12.+(6.*13.)/42.;
does what you are expecting.