.decimalPlaces()

๐Ÿ’พ ็จ‹ๅผ๏ผš replit

// 2022.02.15

import Foundation        // for NSString: String(format:)

extension FloatingPoint where Self: CVarArg {
    /// show a floating-point number to specified decimal places.
    /// ```
    /// (1.2345).decimalPlaces(3)  // "1.234"
    /// (1.2).decimalPlaces(3)     // "1.200"
    /// ```
    public func decimalPlaces(_ n: Int) -> String {
        return String(format: "%.\(n)f", self)
    }
}

๐Ÿ’ˆ็ฏ„ไพ‹๏ผš

(1.2345).decimalPlaces(3)         // "1.234"
(1.2).decimalPlaces(3)            // "1.200"
Float(45.678).decimalPlaces(2)    // "45.68"

Last updated