简体   繁体   English

iOS:更正NSDecimalNumber计算

[英]iOS: Correct NSDecimalNumber calculations

First time using NSDecimalNumber, so I've wondered do I really need to create so many objects? 第一次使用NSDecimalNumber,所以我想知道我真的需要创建这么多对象吗? In my method I want to calculate monthly costs out of daily costs. 在我的方法中,我想计算每日成本中的每月费用。 The monthly costs are stored in self.sumPerMonth and the parameter costs is the daily cost value. 每月费用存储在self.sumPerMonth ,参数costs是每日费用值。 So I want to add to my monthly costs 30 * costs . 所以我想增加每月费用30 * costs Is this the easiest way to do that? 这是最简单的方法吗?

[self.sumPerMonth decimalNumberByAdding:[costs decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:@"30"]]];

NSDecimalNumber is immutable so yes, you need to create a new object each time you do an operation. NSDecimalNumber是不可变的,所以是的,每次执行操作时都需要创建一个新对象。

The clumsiness of dealing with the objects is the compromise you make for getting base-10 calculations without loss of precision and with predictable rounding behavior . 处理对象的笨拙是你在不损失精度和可预测的舍入行为的情况下进行基础10计算的折衷方案。

Beware of mixing NSNumber and NSDecimalNumber . 注意混合NSNumberNSDecimalNumber

A little reading: http://rypress.com/tutorials/objective-c/data-types/nsdecimalnumber.html 一点阅读: http//rypress.com/tutorials/objective-c/data-types/nsdecimalnumber.html

Yes, that's the way to go using NSDecimalNumber . 是的,这是使用NSDecimalNumber

If there's valid reason to be concerned about number of objects created you could switch to the plain NSDecimal struct type. 如果有正当理由关注创建的对象数量,您可以切换到纯NSDecimal结构类型。 The difference is that NSDecimal is mutable. 区别在于NSDecimal是可变的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM