Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 437
William T. Avatar asked Oct 22 '25 11:10

William T.


2 Answers

.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)))
like image 96
Joakim Danielson Avatar answered Oct 25 '25 01:10

Joakim Danielson


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))
like image 37
lorem ipsum Avatar answered Oct 25 '25 00:10

lorem ipsum