Getting the decimal part of a double in Swift

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

    You can get the Integer part like this:

    let d: Double = 1.23456e12
    
    let intparttruncated = trunc(d)
    let intpartroundlower = Int(d)
    

    The trunc() function truncates the part after the decimal point and the Int() function rounds to the next lower value. This is the same for positive numbers but a difference for negative numbers. If you subtract the truncated part from d, then you will get the fractional part.

    func frac (_ v: Double) -> Double
    {
        return (v - trunc(v))
    }
    

    You can get Mantissa and Exponent of a Double value like this:

    let d: Double = 1.23456e78
    
    let exponent = trunc(log(d) / log(10.0))
    
    let mantissa = d / pow(10, trunc(log(d) / log(10.0)))
    

    Your result will be 78 for the exponent and 1.23456 for the Mantissa.

    Hope this helps you.

提交回复
热议问题