Antonio MG
Antonio MG

Reputation: 20410

Objective c: Parsing string to float, avoid extra decimals

Im converting some information Im receiving by a string to a float to get the sum of all of them.

The problem is when I convert the float, for example:

myString = @"13502.63"
float *f = [myString floatValue];
NSLog(@"Converted %f", f);

The result of "f" is 13502.629883

This thing is ok for some values, but when I have to add a big amount of this values, these extra decimals make the result incorrect.

Could anybody help me, please?

Thanks

Upvotes: 0

Views: 1366

Answers (3)

sergio
sergio

Reputation: 69027

float numbers have no exact representation, that is the reason why "13502.63" is converted to 13502.629883; this is the closest float to the original number.

So, I don't think there is an easy solution with float. You should try NSDecimalNumber. I don't know about the performance, but it should give you an exact representation.

Upvotes: 1

iandotkelly
iandotkelly

Reputation: 9124

Unfortunately all floating point types in any language will have this problem, as they have to convert into an underlying binary integer format.

Have you considered using NSDecimalNumber?

These will be much slower than a float, but if that is not a problem, then they are much more accurate for such calculations.

If you need speed for some reason, would a double or long-double be accurate enough?

Upvotes: 1

Matthias Bauch
Matthias Bauch

Reputation: 90117

If you want accuracy you should not use float. Use NSDecimalNumber.

NSString *myString = @"13502.63";
NSDecimalNumber *number = [NSDecimalNumber decimalNumberWithString:myString];

Upvotes: 2

Related Questions