Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MeasurementFormatter not working as intended

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?

like image 568
Big Alex Avatar asked Dec 20 '25 04:12

Big Alex


1 Answers

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.

like image 112
Justin Ganzer Avatar answered Dec 21 '25 21:12

Justin Ganzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!