gpt4 book ai didi

ios - NSDecimalNumber 如何判断是否有小数部分

转载 作者:行者123 更新时间:2023-11-30 13:47:05 25 4
gpt4 key购买 nike

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

我在计算属性中执行此操作,因此我希望它尽可能高效。这是我的扩展目前在 Playground 上的样子:

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);
}

最佳答案

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

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

关于ios - NSDecimalNumber 如何判断是否有小数部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34794733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com