Gypsa
Gypsa

Reputation: 11314

Rounding off float value to one value after decimal

I am working on a code where I have a float value like 29.8888 and when i do as:-

float value=29.8888
NSLog(@"value=%0.2f",value);

I got 29.8 that is perfectly fine now i want to assign this value in another float variable.I dont know how to do this please help

thanks in advance!

Upvotes: 1

Views: 2272

Answers (2)

Joetjah
Joetjah

Reputation: 6132

float roundedValue = round(2.0f * number) / 2.0f;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; 
[formatter setMaximumFractionDigits:1]; 
[formatter setRoundingMode: NSNumberFormatterRoundDown];  
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]]; 
[formatter release];

I found this, this should be self explaining. Another, easy and cheap way:

float f = 29.8888; 
int i = f *10; // 298 
float answer = i/10.0f; //29.8

Upvotes: 5

reflog
reflog

Reputation: 7645

float z = [[NSString stringWithFormat:@"%0.2f", value, nil] floatValue];

Upvotes: -1

Related Questions