将NSString转换为Float - 添加小数位数? [英] Converting NSString to Float - Adds in Decimal Places?
问题描述
我解析从内容如下(部分提取物)的XML文件中的一些顶点信息:
21081.7 23447.6 2781.62 24207.4 18697.3 -2196.96
将字符串保存为NSString,然后转换为浮点值(我将后来馈入OpenGL ES)
pre $ N $ C $ xPoint = [finishedParsingArray objectAtIndex:baseIndex];
NSLog(@xPoiint is%@,xPoint);
float x = [xPoint floatValue];
问题在于float x更改如下值:
'pre> 21081.699219,23447.599609,2781.620117,24207.400391,18697.300781,-2196.959961
正如你所看到的,它正在改变小数位数(不知道它是如何做的 - 必须在xml文件中隐藏格式?)
我的问题是,如何将float与NSString / XML文件中的原始数字匹配到相同的小数位数?
预先感谢!
你的问题似乎是你不明白浮动
存储在内存中,不知道浮点数不精确。
精确值通常无法存储,因此系统会选取最接近的数字来表示它。如果仔细观察,可以看到每个输出的数字都非常接近您输入的值。
为了获得更好的准确性,请尝试使用 double改为
。双确实遇到同样的问题,但更好的精度。花车约有6位有效数字;双打比两倍多。 Source
这里有一些其他的StackOverflow答案和外部文章,你应该阅读:
- 什么每台计算机科学家应该知道关于浮点运算
- 的浮在维基百科
-
$ / $> bI am parsing some vertice information from an XML file which reads as follows (partial extract) :
21081.7 23447.6 2781.62 24207.4 18697.3 -2196.96
I save the string as an NSString and then convert to a float value (which I will later feed into OpenGL ES)
NSString * xPoint = [finishedParsingArray objectAtIndex:baseIndex]; NSLog(@"xPoiint is %@", xPoint); float x = [xPoint floatValue];
The problem is that float x changes the values as follows :
21081.699219, 23447.599609, 2781.620117, 24207.400391, 18697.300781, -2196.959961
As you can see, it is changing the number of decimal places (not sure how it is doing this - must be hidden formatting in the xml file ?)
My question is how can I store the float to match the original number in the NSString / XML file to the same number of decimal places ?
Thanks in advance !
解决方案Your issue seems to be that you don't understand how
floats
are stored in memory and don't know that floats aren't precise.Exact values often can't be stored and so the system picks the closest number it can to represent it. If you look carefully, you can see that each of the outputted numbers is very close to your inputted values.
For better accuracy, try using
double
instead. Double does encounter the same problems, but with better precision. Floats have about 6 significant digits; doubles have more than twice that. SourceHere are some other StackOverflow answers and external articles you should read:
- What Every Computer Scientist Should Know About Floating-Point Arithmetic
- Floating Points on Wikipedia
- This answer on a similar question
这篇关于将NSString转换为Float - 添加小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
点