First you should use Swift Decimal
type if you would like to preserve your fractional digits precision. Second to get its fraction value you can check this post. Once you have your decimal fractions all you need is to get their significand value:
extension Decimal {
func rounded(_ roundingMode: NSDecimalNumber.RoundingMode = .bankers) -> Decimal {
var result = Decimal()
var number = self
NSDecimalRound(&result, &number, 0, roundingMode)
return result
}
var whole: Decimal { self < 0 ? rounded(.up) : rounded(.down) }
var fraction: Decimal { self - whole }
}
let a1 = Decimal(string: "2.5")!
let a2 = Decimal(string: "7.63")!
let a3 = Decimal(string: "8.81")!
let a4 = Decimal(string: "99")!
let a1Frac = a1.fraction // 0.5
let a2Frac = a2.fraction // 0.63
let a3Frac = a3.fraction // 0.81
let a4Frac = a4.fraction // 0
let a1significand = a1Frac.significand // 5
let a2significand = a2Frac.significand // 63
let a3significand = a3Frac.significand // 81
let a4significand = a4Frac.significand // 0
If you need to convert your Decimal
values to Int
you can simply cast it to NSDecimalNumber
and get its intValue
or add those extensions to your project to add the same NSDecimalNumber
functionality to Swift Decimal
type:
extension Decimal {
var decimalNumber: NSDecimalNumber { self as NSDecimalNumber}
var intValue: Int { decimalNumber.intValue }
}
a1significand.intValue // 5
a2significand.intValue // 63
a3significand.intValue // 81
a4significand.intValue // 0