扩展十进制以使用舍入(basedToBehavior :)

时间:2016-12-23 11:36:56

标签: swift math

我正在使用Swift中的Decimal类型的数字。我想将rounding(accordingToBehavior:)与我的号码一起使用,为此我相信我需要写一个Decimal的扩展名来使用NSDecimalNumber的这种方法。我不知道该怎么做,因为我以前从未写过扩展名。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

你试过这样的事吗。

let testingNSDecimalNumber: NSDecimalNumber = 8.765 
let numberHandler = NSDecimalNumberHandler(roundingMode: .plain, scale: 2, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
let roundedDecimalNumber = testingNSDecimalNumber.rounding(accordingToBehavior: numberHandler)

如果您想创建extension NSDecimalNumber,那么您可以尝试这样做。

extension NSDecimalNumber {
    func makeRoundingNumber(with scale: Int16) -> NSDecimalNumber {
        let numberHandler = NSDecimalNumberHandler(roundingMode: .plain, scale: scale, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
        return self.rounding(accordingToBehavior: numberHandler)
    }
}

现在以这种方式调用此扩展程序的方法。

let testingNSDecimalNumber: NSDecimalNumber = 8.765
print(testingNSDecimalNumber.makeRoundingNumber(with: 2))

修改:对于您的评论If var testingDecimalNumber: Decimal = 8.765 is a Decimal I cannot invoke .rounding(accordingToBehavior:),您可以尝试这样做。

extension Decimal {
    func makeRoundingNumber(with scale: Int16) -> NSDecimalNumber {
        let numberHandler = NSDecimalNumberHandler(roundingMode: .plain, scale: scale, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false)
        return NSDecimalNumber(decimal: self).rounding(accordingToBehavior: numberHandler)
    }
}

现在就这样称呼它。

var testingDecimalNumber: Decimal = 8.765
print(testingDecimalNumber.makeRoundingNumber(with: 2))