Search code examples
swiftmeasurementformatter

Swift measurementFormatter from Celsius not working


I am just starting with swift. This is what I have in my playground...

let tempF1 = Measurement(value: 98.6, unit: UnitTemperature.fahrenheit)  
let tempC1 = tempF1.converted(to: UnitTemperature.celsius)  
let convertedTemperature1 = MeasurementFormatter().string(from: tempC1)

Output:
98.6 °F
37.0000000000025 °C.
"98.6°F"

let tempC2 = Measurement(value: 37, unit: UnitTemperature.celsius)  
let tempF2 = tempC2.converted(to: UnitTemperature.fahrenheit)  
let convertedTemperature2 = MeasurementFormatter().string(from: tempF2)

Output:
37.0 °C
98.59999999999546 °F
"98.6°F"

As you can above, formatting Fahrenheit works but Celsius does not...

Any clue what I am doing wrong here??

thanks


Solution

  • The formatting is working correctly.

    MeasurementFormatter outputs the value in the correct format for its locale setting, which defaults to the .current. This means whatever unit you use to create the variable, it will always be displayed in the unit corresponding to the formatter's locale.

    Specifically setting the locale will change the output

    let mf = MeasurementFormatter()
    let temp = Measurement(value: 37.3, unit: UnitTemperature.celsius)
    mf.locale = Locale(identifier: "en_GB")
    print(mf.string(from: temp))
    mf.locale = Locale(identifier: "fr_FR")
    print(mf.string(from: temp))
    mf.locale = Locale(identifier: "en_US")
    print(mf.string(from: temp))
    

    This outputs:

    37.3°C       - UK format, in Celsius, and with a period separator

    37,3 °         - French format in Celsius, and with a comma separator

    99.14°F     - USA format, in Fahrenheit, and with a comma separator