检查double值是否为整数 - Swift [英] Checking if a double value is an integer - Swift

查看:665
本文介绍了检查double值是否为整数 - Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查一个双重定义的变量是否可转换为Int而不失去其值。这不起作用,因为它们有不同的类型:

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)

其中 self.value 是一个双重的。 p>

where self.value is a double.

推荐答案

尝试'flooring'双重值,然后检查是否不变:

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

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

如果不是整数,则失败

let dbl = 2.4
let isInteger = floor(dbl) == dbl // false

这篇关于检查double值是否为整数 - Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆