Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift get Fraction of Float

I've been trying out swift lately and i've come across a rather simple Problem.

In Obj-C when i want to get the fraction digits of a float i'd do the following:

float x = 3.141516
int integer_x = (int)x;
float fractional_x = x-integer_x;
//Result: fractional_x = 0.141516

in Swift:

let x:Float = 3.141516
let integerX:Int = Int(x)
let fractionalX:Float =  x - integerX 

-> this results in an error because of mismachting types

Any Idea how to do it correctly?

Thanks in Advance

Malte

like image 908
Malte Avatar asked Jul 28 '14 14:07

Malte


2 Answers

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

like image 87
zaph Avatar answered Nov 17 '22 20:11

zaph


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.

like image 44
Henning Avatar answered Nov 17 '22 20:11

Henning