在Swift中测试十进制是否为整数 [英] Testing if a Decimal is a whole number in Swift

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

问题描述

使用Swift 3。

我在网上发现了许多奇怪的解决方案,用于检查 十进制 对象是一个整数。一切都比需要的复杂得多。

I am finding a lot of strange solutions online for checking if a Decimal object is a whole number. Everything feels far more complicated then it needs to be.

这是我的解决方法:

extension Decimal {
    var isWholeNumber: Bool {
        return self.exponent == 1
    }
}

在我的测试中,此方法有效。我的问题是我缺少明显的东西吗?

In my tests this works. My question is am I missing something obvious?

推荐答案

感谢您的评论!这是我现在正在使用的。

Thanks for the comments! Here is what I am using now.

extension Decimal {
    var isWholeNumber: Bool { 
        return self.isZero || (self.isNormal && self.exponent >= 0) 
    }
}

这篇关于在Swift中测试十进制是否为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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