sribharanidharan subramanian sribharanidharan subramanian - 6 months ago 45
iOS Question

Stop Float value rounding off in objective c

I have to prevent the value from rounding off after the decimal.

Here is the code I use :

NSNumberFormatter* nf = [[[NSNumberFormatter alloc] init] autorelease];
nf.positiveFormat = @"0.###";
NSString* trimmedValue = [nf stringFromNumber: [NSNumber numberWithFloat:[exRateLabel doubleValue]*amount]];
trimmedValue = [trimmedValue substringToIndex:[trimmedValue length]-1];


In this case, if I multiply 1000 * 50.1234 I'm getting 50123.3984, but it should be 50123.4.

NSLog(@".2f",50.1234*1000);


For this case it's showing the correct value but for

NSLog(@".2f",50.1234*123);


it is rounding off the actual value, which is 6165.1782, to 6165.18.

Answer

Just use double instead of float and a proper rounding rule:

NSNumberFormatter* nf = [[NSNumberFormatter alloc] init];
nf.positiveFormat = @"0.###";
nf.roundingMode = NSNumberFormatterRoundFloor;
NSString* trimmedValue = [nf stringFromNumber: [NSNumber numberWithDouble:50.1234*123]];
NSLog(@"trimmedValue: %@", trimmedValue);

And the result is:

trimmedValue: 6165.178