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


i here problem: have nsstring contain "1.7" (for example) , have float number = 1.7 i' ve tried [mystring floatvalue] result 1.700000000004576 if try "1.74" result 1.74000000000000000067484 how can fix it? thank you!

you correctly converting string float. problem floating point numbers cannot represent real numbers exactly. direct assignment:

float x = 1.7; 

will still have precision error. that's how floating point numbers are.

the workaround depends on needs. examples: if need more precision mathematical calculations, can use doubles. if you're trying generate output user, can format output limits number of digits shown after decimal point. if you're dealing money, convert floating point dollar amounts integer numbers of cents , perform calculations using integers, showing decimal point on output user.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -