我有一个用例,我想确定 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);
}