7

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
ajrlewis
  • 2,968
  • 3
  • 33
  • 67

1 Answers1

8

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"
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571