0

I have tried code below. My expectation is isDecimal("56.0") should return true. And isDecimal("56") should return false, also isDecimal(".") should return false but the function is returning true always. Please anyone help in this issue.

func isDecimal(str : String) -> Bool {
    if let _ = Decimal(string: str) {
        return true
    }
    return false
}

I have to verify there is always a integer after (dot). like 15.0 or 15.1. It should not be 15.a or 15. or 15.#

adil Raza
  • 1
  • 1
  • What exactly is your definition of a "decimal"? – Sweeper Aug 17 '22 at 14:01
  • A decimal is a number that consists of a whole and a fractional part. like 56.0 , 15.5 – adil Raza Aug 17 '22 at 14:03
  • Why not simply `Decimal(string: str) != nil`? – Leo Dabus Aug 17 '22 at 14:17
  • Thanks @LeoDabus for your reply but checkDecimal(str: "56") is returning true not false, as "56" is not having any fraction. Tried func checkDecimal(str : String) -> Bool { Decimal(string: str) != nil } – adil Raza Aug 17 '22 at 14:29
  • Your expectation is wrong: `Decimal(string: str)` will only fail if `str` is not a number at all. E.g. `isDecimal("fifty-six")` will fail. You need to do something like this instead: https://stackoverflow.com/questions/25552648/check-if-number-is-decimal-with-swift – timbre timbre Aug 17 '22 at 14:30
  • @sfgblackwarkrts suggested answer will fail when I will check for 56.0 as it is having decimal 0 after the number. 56.0 - floor(56.0) > 0 . – adil Raza Aug 17 '22 at 15:14
  • 1
    @adilRaza My point was that you are building on wrong expectation. The post I linked gives several ways to check for decimal. You can also (since your input is string) use a regex (this is what I would do actually). Or you can try to split the string by decimal character (locale specific) and see if you have 2 tokens. There are many ways. None of them includes converting to decimal though – timbre timbre Aug 17 '22 at 15:20
  • I also have to verify there is always a single integer after (dot). like 15.0 or 15.1. It should not be 15.a or only 15. or 15.# – adil Raza Aug 17 '22 at 16:08

0 Answers0