Home > Software design >  How to compare the values which overflows the upper bound in swift?
How to compare the values which overflows the upper bound in swift?

Time:06-04

Swift Limit is to store biggest Integer Value is (Int64):9223372036854775807

Need to compare: 20000000000000000000

That is larger than the max value , How can I tell that it is beyond upper bound, it simply overflows. Can’t compare.

I need to return 2147483648 if entered value crossed 9223372036854775807

Any suggestions? I know it can be simple enough, but no idea at the moment.

CodePudding user response:

You can use Swift Decimal type:

let value = "20000000000000000000"
let maxValue = Decimal(Int64.max)

if let decimalValue = Decimal(string: value) {
    if decimalValue > maxValue {
        print("\(value) overflows Int64 max \(maxValue)")
    }
}

CodePudding user response:

Use a Double or Decimal type.

Doubles can store very large magnitude numbers, with a slight loss of precision compared to 64 bit ints (64 bit Doubles store 53 bits of "significand" value, so to get to values bigger than 2⁵³ you won't be able to count by ones.)

  • Related