Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing if a Decimal is a whole number in Swift

Tags:

decimal

swift

Using Swift 3.

I am finding a lot of strange solutions online for checking if a Decimal object is a whole number. Everything feels far more complicated then it needs to be.

Here is my solution:

extension Decimal {
    var isWholeNumber: Bool {
        return self.exponent == 1
    }
}

In my tests this works. My question is am I missing something obvious?

like image 828
mgChristopher Avatar asked May 17 '17 19:05

mgChristopher


2 Answers

Thanks for the comments! Here is what I am using now.

extension Decimal {
    var isWholeNumber: Bool { 
        return self.isZero || (self.isNormal && self.exponent >= 0) 
    }
}
like image 70
mgChristopher Avatar answered Oct 17 '22 03:10

mgChristopher


Here is a translation of the Objective-C solution in Check if NSDecimalNumber is whole number to 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

This works even if the mantissa is not minimal (or the exponent not maximal), such as 100 * 10-1. Example:

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
like image 21
Martin R Avatar answered Oct 17 '22 02:10

Martin R