2

I'm doing some currency math and thus using the Decimal type. I want to test if a decimal number is an integer number (i.e a positive or negative whole number not the Int type). There's no modulus operator for Decimal in Swift, otherwise I'd just use that.

My understanding of decimal types is that they represent numbers as integer * exponent. Thus any integer number will have an exponent ≥ 0, and any number with a fraction component will have an exponent < 0.

Am I correct in my understanding, and this sample would be accurate?

if someDecimal.exponent >= 0 {
   print("Integer")
}
else {
   print("Fraction")
}
robmathers
  • 3,028
  • 1
  • 26
  • 29
  • try this way `let isInteger = someDecimal.truncatingRemainder(dividingBy: 1) == 0` – Nazmul Hasan Sep 20 '17 at 19:54
  • 1
    @NazmulHasan he is using Decimal type – Leo Dabus Sep 20 '17 at 19:55
  • 1
    Well, it appears that non-canonical Decimals are possible -- I imagine that would be something like 100*10^(-1). I don't see a way to ensure that a Decimal is canonical. Maybe instead of looking at the exponent, you can inspect someDecimal._ulp and see if it >= 1 ? – Robert Dodier Sep 20 '17 at 19:55
  • 1
    @RobertDodier no need to use underscore – Leo Dabus Sep 20 '17 at 19:56
  • 1
    @LeoDabus thanks, autocomplete seemed to like _ better, but you're right. – robmathers Sep 20 '17 at 20:03
  • @RobertDodier there is a `isCanonical` property, but [it's always true](https://github.com/apple/swift/blob/2e5817ebe15b8c2fc2459e08c1d462053cbb9a99/stdlib/public/SDK/Foundation/Decimal.swift#L97). What does being canonical (or not) mean in the context of `Decimal`? – robmathers Sep 20 '17 at 20:04
  • Here https://stackoverflow.com/questions/12298755/check-if-nsdecimalnumber-is-whole-number are some solutions for NSDecimalNumber in Objective-C, they can easily be translated to Swift. – Martin R Sep 20 '17 at 20:07
  • 1
    And here is the same question for Swift: https://stackoverflow.com/questions/44033762/swift-decimal-iswholenumber. – Martin R Sep 20 '17 at 20:09
  • Thanks all. Seems that the question Martin linked has the correct answer. I was close, but need to check that it is a normal number. Oddly that question didn't come up in Google or SO search for me. – robmathers Sep 20 '17 at 20:25
  • You can have an integer decimal with a negative exponent (as @RobertDodier said), but you have to "hand-craft" such a number. I have added another answer to the duplicate which covers that case as well. – Martin R Sep 20 '17 at 20:31

0 Answers0