Testing if decimal integer in Swift

Using Swift 3.

I find many strange solutions on the Internet by checking if the Decimal object is an integer. Everything feels a lot more complicated than it should be.

Here is my solution:

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

In my tests, this works. My question is: will I miss something obvious?

+5
source share
3 answers

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

 extension Decimal { var isWholeNumber: Bool { return self.isZero || (self.isNormal && self.exponent >= 0) } } 
+5
source

The following is a translation of the Objective-C solution to Check if NSDecimalNumber is an integer for 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 indicator is not maximum), for example 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 
+2
source

I'm not sure what might work in all cases, but this might be a more consistent option

 extension Decimal { static var decimalSeparator: String { return NumberFormatter().decimalSeparator } var isFraction: Bool { return self.description.contains(Decimal.decimalSeparator) } var isWhole: Bool { return !isFraction } } 
0
source

Source: https://habr.com/ru/post/1432704/


All Articles