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
CodePudding user response:
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))
CodePudding user response:
.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)))