2
let userDefined = Measurement(value: Double(userInput.text!)!, unit: UnitMass.kilograms)

let calculatedValue = userDefined.converted(to: UnitMass.grams)

print(calculatedValue)

let formatter = MeasurementFormatter()
formatter.locale = Locale(identifier: "en_US")
Convertedunit.text = formatter.string(from: calculatedValue)

The user input is 5.

The output of print(calculatedValue) is 5000.0g.

However, the output of Convertedunit.text is 11.003lbs which is in pounds. I tried to use different methods, but it is still not in grams. Can anyone enlighten me?

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
Big Alex
  • 23
  • 4

1 Answers1

1

Because of formatter.locale = Locale(identifier: "en_US"), the formatter will automatically convert everything to the imperial unit system, which in this case is pounds. Grams on the other hand belong to the metric system.

There are two ways to change this behaviour:

A) If you want to use the metric system specify a locale for a country that uses it, such as Germany. formatter.locale = Locale(identifier: "de_DE"). Don't worry, this will not affect the language of the string ( such as German: Meter, English: Meters, French: Mètres) as that is still bound to the apps language.

B) If you want to keep whatever unit you put into the formatter simply declare: formatter.unitOptions = .init(arrayLiteral: .providedUnit) That way the formatter will generate strings with whatever unit you have provided it with.

Justin Ganzer
  • 582
  • 4
  • 15