I here is the problem:
I have a NSString that contain "1.7" (for example) and I have to get the float number = 1.7
I' ve tried with [mystring floatValue]
but the result is 1.700000000004576
If I try with "1.74" the result is 1.74000000000000000067484
how can I fix it?
thank you!
4 Answers
You are correctly converting the string into a float. The problem is that floating point numbers cannot represent all real numbers exactly. A direct assignment:
float x = 1.7;
will still have a precision error. That's just how floating point numbers are.
The workaround depends on your needs. Some examples: If you need more precision for mathematical calculations, you can use doubles. If you're trying to generate output for the user, you can format the output so it limits the number of digits shown after the decimal point. If you're dealing with money, you could convert floating point dollar amounts into integer numbers of cents and perform all calculations using integers, only showing a decimal point on output to the user.

- 8,410
- 5
- 34
- 39
-
thank you for you tempestive answer.the problem is that I have to insert a float value into an sqlite db and then use this float value for make some query in the web, i need to put 1.7 into my db it is possible to round this value? – Daniele Dec 01 '10 at 17:42
-
Would you be able to use the original string for the query? Then you could store the string in your db. Once you convert the string to a float, you'll have no way of knowing whether the original value was 1.7 or 1.700000000004576. – James Huddleston Dec 01 '10 at 17:50
-
now I understood, thank you so much! i used the string instead of the float and it work fine. – Daniele Dec 01 '10 at 18:02
Floats need to be able to represent infinitely many real numbers, but a float contains a finite number of bits, so floats are approximations.
See this article for more.
You can trim the answer by using the formatting below. The .1 will set the result to one decimal place.
NSLog(@"mystring = %.1f ",[mystring floatValue]);

- 6,805
- 2
- 25
- 44
-
yes but I don't know if I have to keep the first or the second decimal. thank you! – Daniele Dec 06 '10 at 11:23