Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
數字處理大全
extension Double {
/// 無條件進位至小數
/// - Parameter decimal: 第幾位
func ceiling(toDecimal decimal: Int) -> Double {
let numberOfDigits = abs(pow(10.0, Double(decimal)))
if self.sign == .minus {
return Double(Int(self * numberOfDigits)) / numberOfDigits
} else {
return Double(ceil(self * numberOfDigits)) / numberOfDigits
}
}
/// 無條件進位至整數
/// - Parameter decimal: 第幾位
func ceiling(toInteger integer: Int = 1) -> Double {
let integer = integer - 1
let numberOfDigits = pow(10.0, Double(integer))
return Double(ceil(self / numberOfDigits)) * numberOfDigits
}
/// 四捨五入至小數
/// - Parameter decimal: 第幾位
func rounding(toDecimal decimal: Int) -> Double {
let numberOfDigits = pow(10.0, Double(decimal))
return (self * numberOfDigits).rounded(.toNearestOrAwayFromZero) / numberOfDigits
}
/// 四捨五入至整數
/// - Parameter decimal: 第幾位
func rounding(toInteger integer: Int) -> Double {
let integer = integer - 1
let numberOfDigits = pow(10.0, Double(integer))
return (self / numberOfDigits).rounded(.toNearestOrAwayFromZero) * numberOfDigits
}
/// 無條件捨去至小數
/// - Parameter decimal: 第幾位
func floor(toDecimal decimal: Int) -> Double {
let numberOfDigits = pow(10.0, Double(decimal))
return (self * numberOfDigits).rounded(.towardZero) / numberOfDigits
}
/// 無條件捨去至整數
/// - Parameter decimal: 第幾位
func floor(toInteger integer: Int) -> Double {
let integer = integer - 1
let numberOfDigits = pow(10.0, Double(integer))
return (self / numberOfDigits).rounded(.towardZero) * numberOfDigits
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.