将 NSString 转换为 Float - 添加小数位?
我正在从 XML 文件中解析一些顶点信息,其内容如下(部分摘录):
21081.7 23447.6 2781.62 24207.4 18697.3 -2196.96
我将字符串保存为 NSString,然后转换为浮点值(稍后我将其输入 OpenGL ES)
NSString * xPoint = [finishedParsingArray objectAtIndex:baseIndex];
NSLog(@"xPoiint is %@", xPoint);
float x = [xPoint floatValue];
问题是 float x 发生变化值如下:
21081.699219, 23447.599609, 2781.620117, 24207.400391, 18697.300781, -2196.959961
如您所见,它正在更改小数位数(不确定它是如何做到这一点的 - 必须在 xml 文件中隐藏格式?)
我的问题是如何存储浮点数以匹配原始值NSString 中的数字 / XML 文件的小数位数相同吗?
提前致谢 !
I 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 !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题似乎是您不了解
浮动
如何存储在内存中,并且不知道浮动不精确。精确值通常无法存储,因此系统会选择最接近的数字来表示它。如果你仔细观察,你会发现每个输出的数字都非常接近你输入的值。
为了获得更高的准确性,请尝试使用
double
代替。 Double 确实遇到了同样的问题,但精度更高。浮点数大约有 6 位有效数字;双打的数量是这个数字的两倍多。 来源以下是您应该阅读的其他一些 StackOverflow 答案和外部文章:
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:
所有存储浮点数的原语都存在精度问题。大多数时候它很小,无关紧要,但有时却至关重要。
当保留确切数字很重要时,我建议使用 NSDecimalNumber.
All primitives which store floating point numbers have an accuracy issue. Most of the time it's so small it doesn't matter, but sometimes it's vital.
When it's important to keep the exact number, I would suggest using NSDecimalNumber.