Possible Duplicate:
How can I round a float value to 2 post decimal positions?
Lets say I have a double number of 3.46. How do I round it to 3.50? I tried
NSLog(@"res: %.f", round(3.46));
but it return 3.
Possible Duplicate:
How can I round a float value to 2 post decimal positions?
Lets say I have a double number of 3.46. How do I round it to 3.50? I tried
NSLog(@"res: %.f", round(3.46));
but it return 3.
Do some calculations....
float f=3.46;
float num=f+0.05;//3.51
int intNum=num*10;//35
float floatNum=intNum/10.0;//3.5
NSLog(@"res: %.2f", floatNum); //3.50
Following code may help
i = roundf(10 * i) / 10.0;
where i is your float variable
If you're willing to live with the rounding rules from printf, then the following should suffice when rounding for presentation:
NSLog(@"res: %.1f0", 3.46);
Note that the 0 is just a normal character that is added after the value is formatted to the appropriate number (1) of decimal places. This approach should be usable with [NSString stringWithFormat:]
as well.
The original code results in "3" because round
always returns an integral value.
YMMV; I don't even use iOS.