NSDecimalNumber如何确定是否存在小数组件

时间:2016-01-14 16:29:35

标签: ios swift computed-properties

我有一个用例,我想确定swift中的NSDecimalNumber是否有一个小数组件(0除外)。我可以截断小数部分,但这涉及创建一个新的NSDecimalNumber,我想尽可能避免这种情况。

我在计算属性中这样做,所以我希望它尽可能高效。目前这是我的扩展在游乐场中的样子:

extension NSDecimalNumber {
    func decimalNumberRoundedToDigits(withDecimals: UInt8, roundingMode: NSRoundingMode = NSRoundingMode.RoundPlain) -> NSDecimalNumber
    {
        // round to required decimals
        let disp = decimalNumberByRoundingAccordingToBehavior(NSDecimalNumberHandler(roundingMode: roundingMode, scale: Int16(withDecimals), raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false));

        return disp;
    }

    //  Convert the least significant byte into a signed 8-bit integer
    // Currently just truncates the fractional portion - I would like
    // to test it instead and only round if there are decimals.
    var safeByteValue: Int8 {
        get {
            let bits = UInt8(decimalNumberRoundedToDigits(0).longLongValue & 0xFF);

            return Int8(bitPattern: bits);
        }
    };
}

// just a test loop for demonstration
for i in 0...256
{
    print(NSDecimalNumber(unsignedInt: UInt32(bitPattern: Int32(i))).safeByteValue);
}

1 个答案:

答案 0 :(得分:0)

我不知道这会有多高效,但确实能给你答案:

extension NSDecimalNumber {
    var hasFractionalComponent: Bool {
        return ("\(num)").unicodeScalars.contains(UnicodeScalar("."))
    }
}