import Foundation
extension Decimal {
var wholePart: Self {
self // ??? what to do here?
}
}
extension Double {
// https://stackoverflow.com/questions/44909637/how-to-get-the-integer-part-and-fractional-part-of-a-number-in-swift
var wholePart: Self {
// all of these seem to work
// modf(self).0
// floor(self)
self.rounded(.towardZero)
}
}
typealias DataType = Double // can be changed to either Decimal or Double
let someValue: DataType = 123.456
// how to get its whole part (123)?
print(someValue.wholePart)
You're looking for NSDecimalRound; unfortunately, I don't believe that it supports rounding toward zero, so you have to fake that:
extension Decimal {
var wholePart: Self {
var result = Decimal()
var mutableSelf = self
NSDecimalRound(&result, &mutableSelf, 0, self >= 0 ? .down : .up)
return result
}
}
3 Likes