使用swift检查数字是否为十进制数 [英] Check if number is decimal with swift

查看:110
本文介绍了使用swift检查数字是否为十进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用swift检查数字是否为小数?

How can i check if a number is decimal or not using swift?

使用Objective-C:

With Objective-C:

if (number == (int) number) {
  //decimal
}
else {
  //not decimal
}


推荐答案

如果你将数字向下舍入(你可以通过使用地板功能),然后从原始数字中减去它,你将得到两者之间的差异。

If you round the number down (which you can do by using the floor function), and then subtract it from the original number, you will get the difference between the two.

if (number - floor(number) > 0.000001) { // 0.000001 can be changed depending on the level of precision you need
    // decimal
}

编辑 -

我的原始答案建议计算数字与其之间的差异地板等效于查看小数点后是否有任何单位。但是,如后面所述,可能存在舍入误差,导致内存中值的表示与实际意义上的值略有不同。

My original answer recommended calculating the difference between the number and its floored equivalent to see if there were any units after the decimal points. However, as later described, there may be a rounding error which causes the representation of a value in memory to be slightly different than what it's actually meant to be.

例如,3.0可以表示为3.00000000000001,因此数字 - 楼层(数字)> 0 将返回true,即使它理论上应该返回false,因为偏移量为0.00000000000001。

For example, 3.0 could be represented as 3.00000000000001, and therefore the number - floor(number) > 0 would return true, even though it should've theoretically returned false as the offset would be 0.00000000000001.

因此请使用@ jessy的回答如下。

这篇关于使用swift检查数字是否为十进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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