Getting the decimal of a double in Swift

I am trying to separate decimal and integer parts of double in swift. I tried several approaches, but they all face the same problem ...

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 the number to a string?

+11
source share
6 answers

Without converting it to a string, you can round to several decimal places as follows:

 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 

Your result will be

0.5678

+13
source

You can use truncatingRemainder and 1 as a delimiter.

Returns the remainder of this value divided by the given value using truncated 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 
+61
source

Swift 2 :

You can use:

 modf(x).1 

or

 x % floor(abs(x)) 
+10
source

Use Float as it has fewer precision digits than Double

 let x:Double = 1234.5678 let n1:Float = Float(x % 1) // n1 = 0.5678 
+6
source

The same approach as Alessandro Ornano, implemented as a property of the FloatingPoint protocol instance:

 public extension FloatingPoint { public var whole: Self { return modf(self).0 } public var fraction: Self { return modf(self).1 } } 

 1.2.whole // 1 1.2.fraction // 0.2 
+1
source

You can get the Integer part as follows:

 let d: Double = 1.23456e12 let intparttruncated = trunc(d) let intpartroundlower = Int(d) 

The trunc () function truncates the part after the decimal point, and the Int () function rounds to the next lower value. This is the same for positive numbers, but the difference is for negative numbers. If you subtract the truncated part from d, then you get the fractional part.

 func frac (_ v: Double) -> Double { return (v - trunc(v)) } 

You can get Mantissa and Exponent of double value as follows:

 let d: Double = 1.23456e78 let exponent = trunc(log(d) / log(10.0)) let mantissa = d / pow(10, trunc(log(d) / log(10.0))) 

Your result will be 78 for the exhibitor and 1.23456 for the Mantissa.

Hope this helps you.

0
source

All Articles