swift:金额(单位为分)计算

/// 金额(单位为分)计算  --self 被除数
/// - Parameters:
///   - scale: 精确度
///   - roundingMode:
/// - Returns:
func dividingMoney(scale: Int16 = 1, roundingMode: NSDecimalNumber.RoundingMode = .plain)  -> String {
    return self.dividing(by: "100",scale: scale, roundingMode: roundingMode)
}

/// 精确计算  --self 被除数
/// - Parameters:
///   - decimalNumber: 除数不为0
///   - scale: 精确度
///   - roundingMode:
/// - Returns:
func dividing(by decimalNumber: String, scale: Int16 = 2, roundingMode: NSDecimalNumber.RoundingMode = .plain)  -> String {
    guard decimalNumber != "0" else {
        return self
    }
    guard self != "0" else {
        return self
    }
    let dec = NSDecimalNumber(string: self)
    let dec1 = NSDecimalNumber(string: decimalNumber)
    let decimalNumberHandler = NSDecimalNumberHandler(roundingMode: roundingMode, scale: scale, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: true)
    let number = dec.dividing(by: dec1, withBehavior: decimalNumberHandler)
    return String(number.doubleValue)
}

你可能感兴趣的:(swift:金额(单位为分)计算)