Getting the decimal part of a double in Swift

前端 未结 9 1465
小鲜肉
小鲜肉 2020-11-28 12:37

I\'m trying to separate the decimal and integer parts of a double in swift. I\'ve tried a number of approaches but they all run into the same issue...

let x:         


        
9条回答
  •  囚心锁ツ
    2020-11-28 13:05

    Swift 5.1

    let x:Double = 1234.5678
    
    let decimalPart:Double = x.truncatingRemainder(dividingBy: 1)    //0.5678
    let integerPart:Double = x.rounded(.towardZero)                   //1234
    

    Both of these methods return Double value.

    if you want an integer number as integer part, you can just use

    Int(x)
    

提交回复
热议问题