diff --git a/Sources/Extensions/AppIntents/Widget/Sensor/WidgetSensorsAppIntentTimelineProvider.swift b/Sources/Extensions/AppIntents/Widget/Sensor/WidgetSensorsAppIntentTimelineProvider.swift index 3dae52e18..406431cb2 100644 --- a/Sources/Extensions/AppIntents/Widget/Sensor/WidgetSensorsAppIntentTimelineProvider.swift +++ b/Sources/Extensions/AppIntents/Widget/Sensor/WidgetSensorsAppIntentTimelineProvider.swift @@ -123,7 +123,12 @@ struct WidgetSensorsAppIntentTimelineProvider: AppIntentTimelineProvider { throw WidgetSensorsDataError.badResponse } - let stateValue = (state?["state"] as? String) ?? "N/A" + var stateValue = (state?["state"] as? String) ?? "N/A" + stateValue = adjustPrecision( + serverId: server.identifier.rawValue, + entityId: sensor.entityId, + stateValue: stateValue + ) let unitOfMeasurement = (state?["attributes"] as? [String: Any])?["unit_of_measurement"] as? String return WidgetSensorsEntry.SensorData( @@ -135,6 +140,39 @@ struct WidgetSensorsAppIntentTimelineProvider: AppIntentTimelineProvider { ) } + private func adjustPrecision(serverId: String, entityId: String, stateValue: String) -> String { + guard let stateValueFloat = Float(stateValue) else { + return stateValue + } + if let decimalPlacesForEntityId: Int = { + do { + return try Current.database.read { db in + try AppEntityRegistryListForDisplay + .filter( + Column(DatabaseTables.AppEntityRegistryListForDisplay.id.rawValue) == ServerEntity + .uniqueId( + serverId: serverId, + entityId: entityId + ) + ) + .fetchOne(db)?.registry.decimalPlaces + } + } catch { + Current.Log.error("Failed to fetch decimal places for entity ID: \(entityId)") + return nil + } + }() { + let numberFormatter = NumberFormatter() + numberFormatter.numberStyle = .decimal + numberFormatter.locale = Locale.current + numberFormatter.maximumFractionDigits = decimalPlacesForEntityId + numberFormatter.minimumFractionDigits = decimalPlacesForEntityId + return numberFormatter.string(from: NSNumber(value: stateValueFloat)) ?? stateValue + } else { + return stateValue + } + } + private func suggestions() async -> [(Server, [HAAppEntity])] { ControlEntityProvider(domains: WidgetSensorsConfig.domains).getEntities() } diff --git a/Sources/Shared/EntityRegistryListForDisplay.swift b/Sources/Shared/EntityRegistryListForDisplay.swift index 682368b75..9c4b4c90c 100644 --- a/Sources/Shared/EntityRegistryListForDisplay.swift +++ b/Sources/Shared/EntityRegistryListForDisplay.swift @@ -29,5 +29,5 @@ public struct AppEntityRegistryListForDisplay: Codable, FetchableRecord, Persist let id: String let serverId: String let entityId: String - let registry: EntityRegistryListForDisplay.Entity + public let registry: EntityRegistryListForDisplay.Entity }