比较 NSDecimalNumber 的不同方法
例如,对于原语,我将这样做,
if ( (x >= 6000) && (x <= 20000) )
// do something here
而对于 NSDecimalNumber,这就是我所拥有的
if ( (([x compare:[NSNumber numberWithInt:6000]] == NSOrderedSame) ||
([x compare:[NSNumber numberWithInt:6000]] == NSOrderedDescending))
&& (([x compare:[NSNumber numberWithInt:20000]] == NSOrderedSame) ||
([x compare:[NSNumber numberWithInt:6000]] == NSOrderedAscending)) )
{
// do something here
}
是否有其他方法(更简单、更优雅)来进行这种比较?如果我将值转换为原始值,我应该使用什么原始值?我不想使用 CGFloat、float 或 double,因为我在这里处理货币。或者,如果我确实将它们转换为上面提到的那些,有人可以验证/解释精度吗?
For example, with primitive, I'll do this
if ( (x >= 6000) && (x <= 20000) )
// do something here
and with NSDecimalNumber, this is what I have
if ( (([x compare:[NSNumber numberWithInt:6000]] == NSOrderedSame) ||
([x compare:[NSNumber numberWithInt:6000]] == NSOrderedDescending))
&& (([x compare:[NSNumber numberWithInt:20000]] == NSOrderedSame) ||
([x compare:[NSNumber numberWithInt:6000]] == NSOrderedAscending)) )
{
// do something here
}
Is there any other ways (easier and more elegant) to this comparison? If I convert the value to primitive, what primitive do I use? I don't want to use CGFloat, float or double, as I'm handling with currency here. Or if I do convert them to those mentioned above, can someone verify / explain about the precision?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我的理解是,您只能使用
compare:
方法比较NSDecimalNumber
和NSNumber
对象。超级令人沮丧,但我相信这是因为 Objective-C 不支持运算符重载。如果它变得真的很难阅读,您总是可以添加一个带有一些辅助方法的类别来尝试使其更具可读性,也许像这样?
然后事情变得更容易理解:
编辑我刚刚注意到您还询问为什么使用 NSDecimalNumber 在货币场景中是最佳的。 这个答案很好地说明了原因使用货币时,浮点数(和双精度数)不够精确。此外, Apple 的 NSDecimalNumber 文档 建议您在进行以 10 为基数的算术运算时使用它。
My understanding is that you can only compare
NSDecimalNumber
andNSNumber
objects using thecompare:
method. Super frustrating, but I believe it stems from Objective-C not supporting operator overloading.If it's becoming really difficult to read, you could always add a category with some helper methods to try and make it a little more readable, something like this perhaps?
Then things become a little more human-readable:
Edit I just noticed that you'd also asked about why using NSDecimalNumber is optimal in currency scenarios. This answer gives a pretty good run down on why floats (and doubles) are not precise enough when working with currency. Furthermore, Apple's documentation for NSDecimalNumber recommends its use whenever you're doing base-10 arithmetic.
NSDecimalNumber+Comparison 类别代码
单元测试以获得良好的测量结果
NSDecimalNumber+Comparison Category Code
Unit Tests for good measure
compare
方法返回NSOrderedDescending
、NSOrderedAscending
或NSOrderedSame
相反,您可以轻松地编写
哪个可读性更好。
compare
method returnsNSOrderedDescending
,NSOrderedAscending
orNSOrderedSame
Instead you can then easily write
Which is slighty better readable.
我认为这也会相当精确。
I think this will be rather preciese too.