Jan
Jan

Reputation: 747

Converting NSString to float produces inexact value

I have two text fields in my view. After prompting the user to enter a value, I convert them to floats to do my calculations.

I use the following code:

variable1 = [textField1.text floatValue];
variable2 = [textField2.text floatValue];`

When the user enters 22.8 in textField1, I get 22.80005 in variable1.

I do not get the exact value!

How do I get the exact decimal value? Any addition could affect the accuracy of the calculations.

Upvotes: 2

Views: 2693

Answers (3)

Ell Neal
Ell Neal

Reputation: 6064

And another question hits SO about floating point accuracy!

You should use NSDecimalNumber instead:

NSDecimalNumber *variable1 = [NSDecimalNumber decimalNumberWithString:[textField1 text]];
NSDecimalNumber *variable2 = [NSDecimalNumber decimalNumberWithString:[textField2 text]];

There's some more info in the Number and Value Programming Guide.

Upvotes: 6

Sulthan
Sulthan

Reputation: 130102

It depends on which calculations you are doing.

For currency use NSDecimalNumber. For other calculations use double instead of a float. The precision problems arise when the number is converted from decadic to binary notation. double will give you better precision (not exact but more precise) and it should be enough for anything you want to do.

There are ways how to do exact calculations on computers but they are more complicated and always are much slower than float or double.

Upvotes: 3

user529758
user529758

Reputation:

You can't: floating point numbers aren't exact values, only estimations, by definition. You are supposed to get such deviations.

Upvotes: 3

Related Questions