Getting the decimal part of a double in Swift

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

    There’s a function in C’s math library, and many programming languages, Swift included, give you access to it. It’s called modf, and in Swift, it works like this

    // modf returns a 2-element tuple,

    // with the whole number part in the first element,

    // and the fraction part in the second element

    let splitPi = modf(3.141592)

    splitPi.0 // 3.0

    splitPi.1 // 0.141592

    You can create an extension like below,

    extension Double {
    
        func getWholeNumber() -> Double {
    
            return modf(self).0
    
        }
    
        func getFractionNumber() -> Double {
    
            return modf(self).1
    
        }
    
    }
    

提交回复
热议问题