Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a double value is an integer - Swift

Tags:

int

double

swift

I need to check if a double-defined variable is convertible to Int without losing its value. This doesn't work because they are of different types:

if self.value == Int(self.value) 

where self.value is a double.

like image 612
Youssef Moawad Avatar asked Feb 11 '15 06:02

Youssef Moawad


People also ask

How do you know if a double is int?

This checks if the rounded-down value of the double is the same as the double. Your variable could have an int or double value and Math. floor(variable) always has an int value, so if your variable is equal to Math. floor(variable) then it must have an int value.

How do you check if a number is an integer in Swift?

main.swift var x = 25 if x is Int { print("The variable is an Int.") } else { print("The variable is not an Int.") }

How do you check if a value is a number in Swift?

Swift Character has a built-in property, isNumber , that can indicate whether the character represents a number or not. We use this property along with allSatisfy to check whether all the characters in a string are a number.


1 Answers

Try 'flooring' the double value then checking if it is unchanged:

let dbl = 2.0 let isInteger = floor(dbl) == dbl // true 

Fails if it is not an integer

let dbl = 2.4 let isInteger = floor(dbl) == dbl // false 
like image 58
ColinE Avatar answered Sep 27 '22 20:09

ColinE