Getting the decimal part of a double in Swift

前端 未结 9 1412
小鲜肉
小鲜肉 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.

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-28 13:23

    Swift 2:

    You can use:

    modf(x).1
    

    or

    x % floor(abs(x))
    
    0 讨论(0)
提交回复
热议问题