fix #4150: display 0°C instead of -0°C for near-zero negative temperatures (#4186)

Signed-off-by: lowi <75674438+lohwasser@users.noreply.github.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
lowi 2026-01-13 13:34:35 +01:00 committed by GitHub
parent 0df3af36c6
commit 80996f241b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 129 additions and 7 deletions

View file

@ -1,5 +1,5 @@
/*
* Copyright (c) 2025 Meshtastic LLC
* Copyright (c) 2025-2026 Meshtastic LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@ -14,21 +14,31 @@
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package org.meshtastic.core.model.util
import kotlin.math.ln
import kotlin.math.roundToInt
object UnitConversions {
@Suppress("MagicNumber")
fun celsiusToFahrenheit(celsius: Float): Float = (celsius * 1.8F) + 32
fun Float.toTempString(isFahrenheit: Boolean) = if (isFahrenheit) {
val fahrenheit = celsiusToFahrenheit(this)
"%.0f°F".format(fahrenheit)
} else {
"%.0f°C".format(this)
/** Formats temperature as a string with the unit suffix. */
fun Float.toTempString(isFahrenheit: Boolean): String {
val temp = if (isFahrenheit) celsiusToFahrenheit(this) else this
val unit = if (isFahrenheit) "F" else "C"
// Convoluted calculation due to edge case: rounding negative values.
// We round the absolute value using roundToInt() (banker's rounding), then reapply the sign so values
val absoluteTemp: Float = kotlin.math.abs(temp)
val roundedAbsoluteTemp: Int = absoluteTemp.roundToInt()
val isZero = roundedAbsoluteTemp == 0
val isPositive = kotlin.math.sign(temp) > 0
val sign: String = if (isPositive || isZero) "" else "-"
return "$sign$roundedAbsoluteTemp°$unit"
}
/**