Skip to content

Instantly share code, notes, and snippets.

@ohlulu
Created March 14, 2020 05:20
Show Gist options
  • Save ohlulu/48b4dda28fdf5211a0b31554b8e0a261 to your computer and use it in GitHub Desktop.
Save ohlulu/48b4dda28fdf5211a0b31554b8e0a261 to your computer and use it in GitHub Desktop.
數字處理大全
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