Swift gets a swim fraction

Recently, I have been trying fast, and I ran into a pretty simple problem.

In Obj-C, when I want to get fractional numbers for a float, I would 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 leads to an error due to mismatch types

Any idea how to do this correctly?

Thanks at Advance

Malta

+5
source share
5 answers

The problem is that you cannot subtract Float and Int, you must convert one of this value to the same as the other, try the following:

let fractionalX:Float = x - Float(integerX)
+3
source

Use function modf:

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

conclusion:

share: 0,141516

For float instead of double just use: modff

+13

.truncatingRemainder(dividingBy:) (x% 1), ( )

  • ( ),
  • (, , )

.

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

fracPart : 0,141516. double float.

+5

Swift 3 %. , truncatingRemainder Double.

let x1:Double = 123.00
let t1 = x1.truncatingRemainder(dividingBy: 1)
print("t1 = \(t1)")
let x2:Double = 123.45
let t2 = x2.truncatingRemainder(dividingBy: 1)
print("t2 = \(t2)")

:

t1 = 0.0
t2 = 0.450000000000003

3 , , , .

+3

int ?

:

import Darwin

let x = 3.1415926
let xf = x - (x > 0 ? floor(x) : ceil(x))

. , :

let x: Float = 3.1415926

, ?

-1

All Articles