简体   繁体   中英

Using Swift ".formatted()" for decimals with trailing zeros removed?

I am trying to remove trailing zeros from doubles, the code I've seen are similar to this .

let formatter = NumberFormatter()
formatter.minimumFractionDigits = 0
formatter.maximumFractionDigits = 2
print(formatter.string(from: 1.0000)!) // 1
print(formatter.string(from: 1.2345)!) // 1.23

Which requires you to create a NumberFormatter(). I know Apple introduced a new.formatted() function recently. Does anyone know if it's possible to do the above with this new system?

The documentation is a bit convoluted for me but so far I've only seen the ability to set the precision.

let string = 1.00000.formatted(.number.precision(.fractionLength(2)))
// 1.00

You can create your own FormatStyle

public struct DecimalPrecision<Value>: FormatStyle, Equatable, Hashable, Codable where Value :  BinaryFloatingPoint{
    let maximumFractionDigits: Int
    public func format(_ value: Value) -> String {
        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = 0
        formatter.maximumFractionDigits = maximumFractionDigits
        
        return formatter.string(from: value as! NSNumber) ?? ""
    }
    
}

extension FormatStyle where Self == FloatingPointFormatStyle<Double> {
    public static func precision (maximumFractionDigits: Int) -> DecimalPrecision<Double> {
        return DecimalPrecision(maximumFractionDigits: maximumFractionDigits)
    }
}

Then use it

let string = 1.00000.formatted(.precision(maximumFractionDigits: 2))

.precision is what you should use and then there is a variant of .fractionLength that takes a range as argument,

10_000.123.formatted(.number.precision(.fractionLength(0…2)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM