开发者

Objective c: Parsing string to float, avoid extra decimals

开发者 https://www.devze.com 2023-03-23 12:51 出处:网络
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:

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


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

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


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号