quangnghiadev / take-notes

0 stars 0 forks source link

Round Double -> Double #1

Open quangnghiadev opened 3 years ago

quangnghiadev commented 3 years ago
func round(numberOfDecimalPlaces: Int, rule: FloatingPointRoundingRule) -> Self {
    let factor = Self(pow(10.0, Double(max(0, numberOfDecimalPlaces))))
    return (self * factor).rounded(rule) / factor
}
quangnghiadev commented 3 years ago

Source https://github.com/SwifterSwift/SwifterSwift/blob/425b82ae37d7ed256b75407e5dae66062b397f3c/Sources/SwifterSwift/SwiftStdlib/BinaryFloatingPointExtensions.swift

quangnghiadev commented 3 years ago
/// SwifterSwift: Returns a rounded value with the specified number of decimal places and rounding rule. If `numberOfDecimalPlaces` is negative, `0` will be used.
///
///     let num = 3.1415927
///     num.rounded(numberOfDecimalPlaces: 3, rule: .up) -> 3.142
///     num.rounded(numberOfDecimalPlaces: 3, rule: .down) -> 3.141
///     num.rounded(numberOfDecimalPlaces: 2, rule: .awayFromZero) -> 3.15
///     num.rounded(numberOfDecimalPlaces: 4, rule: .towardZero) -> 3.1415
///     num.rounded(numberOfDecimalPlaces: -1, rule: .toNearestOrEven) -> 3