4

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.

Community
  • 1
  • 1
user1688346
  • 1,846
  • 5
  • 26
  • 48
  • 1
    It's not [quite] the same as the other question, although the other question will help with part of the task. In this particular example the number should rounded to 3.5 (1 post decimal place) and then present the last 0 in a post-operation (e.g. `%0.2f` or whatever it is) - remember that leading/trailing zeros are not actually part of the value (i.e. 3.5 == 3.50). –  Jan 10 '13 at 08:27

3 Answers3

5

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
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
2

Following code may help

i = roundf(10 * i) / 10.0;

where i is your float variable

Pranjal Bikash Das
  • 1,092
  • 9
  • 27
1

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.

Community
  • 1
  • 1