# Getting the decimal part of a double in Swift

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?

• How to raise a double value by power of 12?
• OCR for Equations and Formulae on the iOS Platform (Xcode)
• Can I force NSExpression and expressionValue to assume Doubles instead of Ints somehow?
• How dangerous is it to compare floating point values?
• iOS: Accurately determining energy of a bump from accelerometer output
• Solve Equations Of Type A*X = B Using dgtsv_ or sgtsv_
• ### 4 Solutions Collect From Internet About “Getting the decimal part of a double in Swift”

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
``````

0.5678

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
``````

Use `Float` since it has less precision digits than `Double`

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

Swift 2:

You can use:

``````modf(x).1
``````

or

``````x % floor(abs(x))
``````