Need both Celsius and Fahrenheit with WeatherKit

791 views Asked by At

I have a weather app that tells the temperature in Celsius and Fahrenheit at the same time. I'd like to use WeatherKit, but I'm having trouble rounding Celsius down to no decimal places. I can do it with Fahrenheit with .formatted because I'm based in the US, but I can't round down Celsius at the same time. Is there an easy way to do that in SwiftUI? Or is it possible to manually set the locale for just a single property?

            if let weather{
                
                let celsiusWeather = weather.currentWeather.temperature.converted(to: .celsius).description
                
                
                VStack{
                    Text("New York")
                        .font(.largeTitle)
                    Text("\(weather.currentWeather.temperature.converted(to: .fahrenheit).formatted().description)")
                    Text(celsiusWeather)
                }
            }
        }

This current code comes up with it half there:

New York 45°F 5.98°C

But I would like it simply be 6°C instead. I've tried string interpolation:

let celsiusFormatted = String(format: "%.0f", celsiusWeather)

and that just came up with 0, not even any of the temperature, so I'm not sure if because it's from WeatherKit that it can do that or not.

Any help would be great. Let me know if you need more code to help clarify.

2

There are 2 answers

3
lorem ipsum On

Try

let celsiusFormatted = String(format: "%.0f", celsiusWeather.value)

celsiusWeather appears to be a measurement not a Double the value of a measurement is a Double.

You can also include precision for a Text

Text(weather.currentWeather.temperature.converted(to: .celsius), format: .measurement(width: .abbreviated, usage: .asProvided,numberFormatStyle: .number.precision(.fractionLength(2))))
0
Ashley Mills On

You can format the temperature using MeasurementFormatter. Remember to set numberFormatter.maximumFractionDigits = 0 to round the number as required and unitOptions = .providedUnit to ensure the correct units are displayed.

struct ContentView: View {
    
    let temp: Measurement<UnitTemperature>
    
    var body: some View {
        VStack {
            HStack {
                Text("New York")
                Text(temp, formatter: formatter)
                Text(temp.converted(to: .celsius), formatter: formatter)
            }
        }
    }
    
    var formatter: MeasurementFormatter {
        let formatter = MeasurementFormatter()
        formatter.unitStyle = .medium
        formatter.numberFormatter.maximumFractionDigits = 0
        formatter.unitOptions = .providedUnit
        return formatter
    }
}

enter image description here