Getting the decimal part of a double in Swift

user3925713 picture user3925713 · Jul 14, 2015 · Viewed 26.9k times · Source

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?

Answer

Nico picture Nico · Mar 2, 2017

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