[英]Objective-C Float / Double precision
I was messing around with storing float
s and double
s using NSUserDefaults
for use in an iPhone application, and I came across some inconsistencies in how the precision works with them, and how I understood it works. 我正在使用
NSUserDefaults
在iPhone应用程序中使用存储float
和double
,我遇到了一些不一致的精度如何与它们一起工作,以及我如何理解它的工作原理。
This works exactly as I figured: 这完全像我想的那样工作:
{
NSString *key = @"OneLastKey";
[PPrefs setFloat:235.1f forKey:key];
GHAssertFalse([PPrefs getFloatForKey:key] == 235.1, @"");
[PPrefs removeObjectForKey:key];
}
However, this one doesn't: 但是,这个没有:
{
NSString *key = @"SomeDoubleKey";
[PPrefs setDouble:234.32 forKey:key];
GHAssertEquals([PPrefs getDoubleForKey:key], 234.32, @"");
[PPrefs removeObjectForKey:key];
}
This is the output GHUnit gives me: 这是GHUnit给我的输出:
'234.320007324' should be equal to '234.32'.
But, if I first cast the double to a float
, and then to a double
it works without fail: 但是,如果我首先将double转换为
float
,然后转换为double
则它会正常工作:
{
NSString *key = @"SomeDoubleKey";
[PPrefs setDouble:234.32 forKey:key];
GHAssertEquals([PPrefs getDoubleForKey:key], (double)(float)234.32, @"");
[PPrefs removeObjectForKey:key];
}
I was under the assumption that numbers entered without an 'f' at the end were already considered double
s. 我假设在最后输入的没有'f'的数字已经被认为是
double
s。 Is this incorrect? 这是不正确的? If so, why does casting to a
float
and then double
work correctly? 如果是这样,为什么要投射
float
然后double
正常工作?
Solved! 解决了! Turns out my framework method
+(void)setDouble:(double)value forKey:(NSString*)key
was actually defined as +(void)setDouble:(
float
)value forKey:(NSString*)key
. 结果我的框架方法
+(void)setDouble:(double)value forKey:(NSString*)key
实际定义为+(void)setDouble:(
float
)value forKey:(NSString*)key
。 The value passed was a double but was converted to a float for use in the method. 传递的值是 double,但转换为float以在方法中使用。 A simple copy and paste issue.
一个简单的复制和粘贴问题。 Too bad the Objective-C compiler didn't at least throw up a warning like it seems to do for everything else...
太糟糕了,Objective-C编译器至少没有像其他一切那样发出警告......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.