Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In a simple calculation

double val = 2011.8 - 1989;

The result of val is 22.777777778 instead of 22.8. Is there any way to round this off????
Posted
Updated 29-Mar-12 0:29am
v5
Comments
Philippe Mori 29-Mar-12 18:22pm    
For sure your example is wrong... There is far too much error in your example. It might be something like 22.799999998 which is really near but not as far as 0.022222222 off. A double has around 15 significant digits.
Sumal.V 30-Mar-12 4:06am    
Well spotted! Sorry, didn't realise in a hurry. I'm glad it is solved now :)

hi
you can use the modf function:
http://www.cplusplus.com/reference/clibrary/cmath/modf/[^]

Best regards
Filipe Marques
 
Share this answer
 
C++
double val = 11.23;
double decimal = val - (int)val;
 
Share this answer
 
Comments
Sumal.V 29-Mar-12 5:50am    
Uh oh!!! Yeah U r right.

But I wanted this so that I can split the decimal number, round it off to a whole number and add up with the integer, so that it would solve my problem.

float val = (2011.8 - 1989);
float decimal = ceil(val - (int)val);

But the ceil or floor rounds up the value to 0 or 1 unfortunately.
Richard MacCutchan 29-Mar-12 6:05am    
Sorry, but I don't quite understand what your problem is, your description is not very clear. Please edit your original question above and try explaining exactly what problem you are trying to solve.
Sumal.V 29-Mar-12 6:30am    
Hi Richard, the question is updated!
Richard MacCutchan 29-Mar-12 6:45am    
You need to understand that using float/double values does not always give accurate results as the decimal part is only ever an approximation of the real number. If you want to round it for display purposes then use the appropriate format parameter in your printf() (or similar) call. If you want exact accuracy of your values then do not use floating point but stick to integers.
Sumal.V 29-Mar-12 6:54am    
Yeah But I ahve to sue double/float in my calculations.

Found the solution! :)
C#
#include <math.h>
:
:
double val = 2011.8 - 1989;
double roundVal = ceilf(val * 100) / 100;
</math.h>
 
Share this answer
 
Comments
Sumal.V 29-Mar-12 6:53am    
Hey Thanks Resmi! that works! need learn more about the ceilf function.
If you want the double value as such use printf , sprintf , snprintf versions they are very fast but use format specifiers properly else it might lead to crashes.

else

you can use math.h functions if you want the round off or floor the values.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900