Getting the decimal part of a double in Swift

别等时光非礼了梦想. 提交于 2019-11-26 08:27:46

问题


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:Double = 1234.5678
let n1:Double = x % 1.0           // n1 = 0.567800000000034
let n2:Double = x - 1234.0        // same result
let n3:Double = modf(x, &integer) // same result

Is there a way to get 0.5678 instead of 0.567800000000034 without converting to the number to a string?


回答1:


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




回答2:


You can use truncatingRemainder and 1 as the divider.

Returns the remainder of this value divided by the given value using truncating division.

Apple doc

Example:

let myDouble1: Double = 12.25
let myDouble2: Double = 12.5
let myDouble3: Double = 12.75

let remainder1 = myDouble1.truncatingRemainder(dividingBy: 1)
let remainder2 = myDouble2.truncatingRemainder(dividingBy: 1)
let remainder3 = myDouble3.truncatingRemainder(dividingBy: 1)

remainder1 -> 0.25
remainder2 -> 0.5
remainder3 -> 0.75



回答3:


Swift 2:

You can use:

modf(x).1

or

x % floor(abs(x))



回答4:


Use Float since it has less precision digits than Double

let x:Double = 1234.5678
let n1:Float = Float(x % 1)           // n1 = 0.5678



回答5:


Same approach as Alessandro Ornano implemented as an instance property of FloatingPoint protocol:

Xcode 11 • Swift 5.1

extension FloatingPoint {
    var whole: Self { modf(self).0 }
    var fraction: Self { modf(self).1 }
}

1.2.whole    // 1
1.2.fraction // 0.2



回答6:


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.



来源:https://stackoverflow.com/questions/31396301/getting-the-decimal-part-of-a-double-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!