我正在努力找出一些看起来应该非常简单的事情。我需要准确地将NSDecimalNumber舍入到特定数量的小数位(在运行时确定)。据我所知,我有两个选项,我都不喜欢。
我错过了另一种方式吗? 得到是一种简单的方法来对NSDecimalNumbers进行舍入,但我似乎无法弄清楚它的生命是什么。
答案 0 :(得分:32)
您只需使用所需的decimalNumberByRoundingAccordingToBehavior:
协议拨打NSDecimalNumberBehaviors
即可。请参阅dev docs中的NSDecimalNumberBehaviors
参考。
更新:请参阅http://www.cimgf.com/2008/04/23/cocoa-tutorial-dont-be-lazy-with-nsdecimalnumber-like-me/
答案 1 :(得分:19)
对于那些喜欢示例代码的人......
要舍入到2位小数(12345.68):
NSDecimalNumber *originalNumber = [NSDecimalNumber decimalNumberWithString:@"12345.6789"];
NSDecimalNumberHandler *behavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain
scale:2
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:NO];
NSDecimalNumber *roundedNumber = [originalNumber decimalNumberByRoundingAccordingToBehavior:behavior];
舍入到最接近的千位(12000):
NSDecimalNumber *originalNumber = [NSDecimalNumber decimalNumberWithString:@"12345.6789"];
NSDecimalNumberHandler *behavior = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain
scale:-3
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:NO];
NSDecimalNumber *roundedNumber = [originalNumber decimalNumberByRoundingAccordingToBehavior:behavior];
答案 2 :(得分:8)
我使用Swift 3中的以下代码工作。
let amount = NSDecimalNumber(string: "123.456789")
let handler = NSDecimalNumberHandler(roundingMode: .plain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
let roundedAmount = amount.rounding(accordingToBehavior: handler)
注意scale参数,用于定义所需的小数位数。在此概述:https://developer.apple.com/reference/foundation/nsdecimalnumberhandler/1578295-decimalnumberhandlerwithrounding
答案 3 :(得分:0)
我正在使用这个解决方案:
import Foundation
extension NSDecimalNumber {
public func round(_ decimals:Int) -> NSDecimalNumber {
return self.rounding(accordingToBehavior:
NSDecimalNumberHandler(roundingMode: .plain,
scale: Int16(decimals),
raiseOnExactness: false,
raiseOnOverflow: false,
raiseOnUnderflow: false,
raiseOnDivideByZero: false))
}
}
let amount = NSDecimalNumber(string: "123.456")
amount.round(2) --> 123.46
amount.round(1) --> 123.5
amount.round(0) --> 123
amount.round(-1) --> 120
amount.round(-2) --> 100