I'm struggling with creating a string representation of a Measurement object that only includes 1 decimal place. Say, for example, that I retrieve temperature information from WeatherKit. The values returned are Measurement objects and I believe the default is degrees Celsius. It is likely that the value will have multiple decimal places, such as 122.2214. I don't want to show four decimal places, just 1.
The Measurement formatting options seem to only involve adding the words or the degree symbol. I've tried many ways to use the .measurement() modifiers but have had no luck.
I can string interpolate as in text fields 4 and 5 in the following code, but I'm not sure that would always work and it does not include the unit descriptors (i.e.deg fahrenheit) that I would otherwise have to kludge together.
Here's some sample code:
struct MeasurementView: View {
let reportedTemperature = Measurement(value: 50.123, unit: UnitTemperature.celsius)
let myLocale = Locale.autoupdatingCurrent
var body: some View {
VStack {
//1
Text(reportedTemperature.formatted())//122.2214 deg F same as abbreviated
//2
Text(reportedTemperature.formatted(.measurement(width: .wide)))//122.2214 degrees Fahrenheit
//3
Text(reportedTemperature.formatted(.measurement(width: .narrow)))
Text("-----")
//4
Text(("\(reportedTemperature.converted(to: .init(forLocale: Locale(identifier: "us_US_POSIX") )).value, specifier: "%.1f")"))
//5
Text(("\(reportedTemperature.converted(to: .init(forLocale: myLocale )).value, specifier: "%.1f")"))
}
}
}
Any guidance would be appreciated. Xcode 15.2, iOS 17.2
Pass a format style that you would usually use to format numbers to the numberFormatStyle
parameter of .measurement
.
let style: Measurement<UnitTemperature>.FormatStyle =
.measurement(
numberFormatStyle: .number.precision(.fractionLength(0...1))
)
Then you can use this like any other measurement format style. Examples:
let measurement = Measurement(value: 50.123, unit: UnitTemperature.celsius)
Text(measurement, format: style)
Text("Some other text \(measurement, format: style)")