Getting the decimal part of a double in Swift

那年仲夏 提交于 2019-11-27 05:17:31

Without converting it to a string, you can round up to a number of decimal places like this:

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 output would be

0.5678

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

Swift 2:

You can use:

modf(x).1

or

x % floor(abs(x))

Use Float since it has less precision digits than Double

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

Same approach as Alessandro Ornano implemented as an instance property of FloatingPoint protocol:

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

You can get the Integer part like this:

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 a difference for negative numbers. If you subtract the truncated part from d, then you will get the fractional part.

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

You can get Mantissa and Exponent of a Double value like this:

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 exponent and 1.23456 for the Mantissa.

Hope this helps you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!