0

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.

2 Answers2

0

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)")
    }
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
0

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.)

Duncan C
  • 128,072
  • 22
  • 173
  • 272