使用Swift 3.
我在网上找到很多奇怪的解决方案,用于检查Decimal对象是否是整数.一切都感觉要复杂得多.
这是我的解决方案:
extension Decimal {
var isWholeNumber: Bool {
return self.exponent == 1
}
}
Run Code Online (Sandbox Code Playgroud)
在我的测试中这是有效的.我的问题是我错过了一些明显的东西吗?
感谢您的评论!这是我现在使用的.
extension Decimal {
var isWholeNumber: Bool {
return self.isZero || (self.isNormal && self.exponent >= 0)
}
}
Run Code Online (Sandbox Code Playgroud)
以下是检查 NSDecimalNumber 是否为整数中的Objective-C 解决方案到 Swift 的翻译:
extension Decimal {
var isWholeNumber: Bool {
if isZero { return true }
if !isNormal { return false }
var myself = self
var rounded = Decimal()
NSDecimalRound(&rounded, &myself, 0, .plain)
return self == rounded
}
}
print(Decimal(string: "1234.0")!.isWholeNumber) // true
print(Decimal(string: "1234.5")!.isWholeNumber) // false
Run Code Online (Sandbox Code Playgroud)
即使尾数不是最小的(或者指数不是最大的),例如 100 * 10 -1 ,这也有效。例子:
let z = Decimal(_exponent: -1, _length: 1, _isNegative: 0, _isCompact: 1, _reserved: 0,
_mantissa: (100, 0, 0, 0, 0, 0, 0, 0))
print(z) // 10.0
print(z.exponent) // -1
print(z.isWholeNumber) // true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
828 次 |
| 最近记录: |