检查double值是否为整数 - Swift

You*_*wad 40 double int swift

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

if self.value == Int(self.value)
Run Code Online (Sandbox Code Playgroud)

哪里self.value是双.

Col*_*inE 72

尝试'铺设'双值,然后检查它是否保持不变:

let dbl = 2.0
let isInteger = floor(dbl) == dbl // true
Run Code Online (Sandbox Code Playgroud)

如果它不是整数则失败

let dbl = 2.4
let isInteger = floor(dbl) == dbl // false
Run Code Online (Sandbox Code Playgroud)

  • 这不能完全解决问题*“ ...,如果双重定义的变量可以转换为Int而不会丢失其值。” *。例如,对于3.1e100,它为true,但是此值不能转换为Int,因为它太大。 (3认同)

rin*_*aro 46

检查是否% 1为零:

斯威夫特3:

let dbl = 2.0
let isInteger = dbl.truncatingRemainder(dividingBy: 1) == 0
Run Code Online (Sandbox Code Playgroud)

斯威夫特2:

let dbl = 2.0
let isInteger = dbl % 1 == 0
Run Code Online (Sandbox Code Playgroud)

  • 如果你能添加一些更多的信息,那就更好了,`%1`会做什么.我认为这将有助于更多人理解代码. (3认同)

Rob*_*ier 21

现在有一个Int(exactly:)初始化程序可以直接告诉您这一点,而不会出现整数超出范围的问题。

if Int(exactly: self) != nil { ... }
Run Code Online (Sandbox Code Playgroud)

如果结果实际上可以精确地存储在 Int 中,则只会返回非零值。有许多 Double 值是“整数”,但不适合 Int。(请参阅 MartinR 对已接受答案的评论。)


Wil*_* T. 19

斯威夫特3

if dbl.truncatingRemainder(dividingBy: 1) == 0 {
  //it's an integer
}
Run Code Online (Sandbox Code Playgroud)


Mus*_*tri 7

简单的解决方案

我建议将值转换为IntthenDouble并检查新值

if value == Double(Int(value)) {
// The value doesn't have decimal part. ex: 6.0

} else {
//  The value has decimal part. ex: 6.3

}
Run Code Online (Sandbox Code Playgroud)


smi*_*Bot 6

迅速的方式:

let cals = [2.5, 2.0]

let r = cals.map{ Int(exactly: $0) == nil ?  "\($0)" : "\(Int($0))" }

r // ["2.5", "2"]
Run Code Online (Sandbox Code Playgroud)

隐藏在扩展中:

extension Array where Element == Double {
    var orExactly: [String] {
        map{ Int(exactly: $0) == nil ?  "\($0)" : "\(Int($0))" }
    }
}

cals.orExactly
Run Code Online (Sandbox Code Playgroud)


Cip*_*rau 5

一个小的扩展来检查这一点:

extension FloatingPoint {
    var isInt: Bool {
        return floor(self) == self
    }
}
Run Code Online (Sandbox Code Playgroud)

然后就做

let anInt = 1.isInt
let nonInt = 3.142.isInt
Run Code Online (Sandbox Code Playgroud)