ajrlewis
ajrlewis

Reputation: 3058

Measurement Formatter: space between value and unit

I have a Measurement attribute:

let measurement = Measurement(value: 10000.0, unit: UnitMass.grams)

that I want to print as a string. I use the following MeasurementFormatter:

let measurementFormatter = MeasurementFormatter()
measurementFormatter.unitStyle = .short
measurementFormatter.numberFormatter.numberStyle = .decimal

print(measurementFormatter.string(from: measurement))

which prints 10,000g.

How can I get it to print 10,000 g, i.e. with a space between the value and the unit?

Upvotes: 8

Views: 1869

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236420

The problem is that you are using the style .short. Just comment out this line and it should display a space between them:

let measurement = Measurement(value: 10000, unit: UnitMass.grams)
let measurementFormatter = MeasurementFormatter()
// measurementFormatter.unitStyle = .short
measurementFormatter.unitOptions = .providedUnit
measurementFormatter.numberFormatter.numberStyle = .decimal
print(measurementFormatter.string(from: measurement))    // "10,000 g\n"

Upvotes: 9

Related Questions