Getting the decimal part of a double in Swift

前端 未结 9 1441
小鲜肉
小鲜肉 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:14

    Without converting it to a string, you can round up to a number of decimal places like this:

    let x:Double = 1234.5678
    let numberOfPlaces:Double = 4.0
    let powerOfTen:Double = pow(10.0, numberOfPlaces)
    let targetedDecimalPlaces:Double = round((x % 1.0) * powerOfTen) / powerOfTen
    

    Your output would be

    0.5678

提交回复
热议问题