Swift get Fraction of Float

Use the modf function:

let v = 3.141516
var integer = 0.0
let fraction = modf(v, &integer)
println("fraction: \(fraction)");

output:

fraction: 0.141516

For float instead of double just use: modff


Use .truncatingRemainder(dividingBy:) which replaced the modulo operator (x % 1), which (for modulo)

  • immediately (it is only one character), and
  • with few cpu cycles (presumably only one cycle, since modulo is a common cpu instruction)

gives the fractional part.

let x:Float = 3.141516
let fracPart =  x.truncatingRemainder(dividingBy: 1) // fracPart is now 0.141516

fracPart will assume the value: 0.141516. This works for double and float.


The problem is that you cannot subtract Float and Int, you should convert one of this value to be the same as another, try that:

let fractionalX:Float = x - Float(integerX)