开发者

How to convert a UTF8 string in a float value in objective-c

I here is the problem: I have a NSString that contain "1.7" (for example) and I have to get the float numb开发者_如何学编程er = 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!


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.


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]);


Solved! I used sqlite3_bind_text even if my database attribute is FLOAT value and I used mystring instead of myfloat and it work fine! Thank you!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜