Move unit formatting to :shared: add expect/actual formatRelativeOrTime, port formatCoords/formatDistance to commonMain (JVM-free), remove app UnitFormat + TimeFormat files, update SettingsContent to use shared formatter
This commit is contained in:
51
shared/src/commonMain/kotlin/app/klottr/util/UnitFormat.kt
Normal file
51
shared/src/commonMain/kotlin/app/klottr/util/UnitFormat.kt
Normal file
@@ -0,0 +1,51 @@
|
||||
package app.klottr.util
|
||||
|
||||
import kotlin.math.abs
|
||||
import kotlin.math.pow
|
||||
import kotlin.math.round
|
||||
import kotlin.math.roundToLong
|
||||
|
||||
// Plattformsgemensamt API (actual i plattformsmappar, Android redan på plats i UnitFormat.android.kt)
|
||||
expect fun formatRelativeOrTime(ms: Long): String
|
||||
|
||||
// Hjälp: format med fast antal decimaler, utan JVM/Locale/printf.
|
||||
private fun formatFixed(value: Double, decimals: Int): String {
|
||||
val factor = 10.0.pow(decimals).roundToLong() // 10^decimals som heltal
|
||||
val scaled = round(value * factor).toLong() // Avrunda till heltal i "skalad" domän
|
||||
val intPart = scaled / factor // Heltalsdelen
|
||||
if (decimals == 0) return intPart.toString() // Ingen decimaldel
|
||||
val fracPart = (scaled % factor).toString().padStart(decimals, '0') // Fyll ut med nollor
|
||||
return "$intPart.$fracPart"
|
||||
}
|
||||
|
||||
// Koordinater: 5 decimaler, kommatecken som svensk decimalavskiljare, NBSP för mellanrum.
|
||||
fun formatCoords(lat: Double, lon: Double): String {
|
||||
val latDir = if (lat >= 0) "N" else "S"
|
||||
val lonDir = if (lon >= 0) "E" else "W"
|
||||
|
||||
val latStr = formatFixed(abs(lat), 5).replace('.', ',') // 5 decimaler
|
||||
val lonStr = formatFixed(abs(lon), 5).replace('.', ',') // 5 decimaler
|
||||
|
||||
return "$latStr° $latDir, $lonStr° $lonDir"
|
||||
}
|
||||
|
||||
// Avstånd: m < 1000 → "m"; < 10 km → "km" med ev. 1 decimal; annars "mil" med ev. 1 decimal.
|
||||
// NBSP (\u00A0) mellan tal och enhet, svensk decimal (komma).
|
||||
fun formatDistance(meters: Int): String {
|
||||
val nbsp = "\u00A0"
|
||||
return when {
|
||||
meters < 1000 -> "$meters${nbsp}m"
|
||||
|
||||
meters < 10_000 -> {
|
||||
val km = meters / 1000.0
|
||||
val s = if (km % 1.0 == 0.0) formatFixed(km, 0) else formatFixed(km, 1)
|
||||
s.replace('.', ',') + "${nbsp}km"
|
||||
}
|
||||
|
||||
else -> {
|
||||
val mil = meters / 10_000.0
|
||||
val s = if (mil % 1.0 == 0.0) formatFixed(mil, 0) else formatFixed(mil, 1)
|
||||
s.replace('.', ',') + "${nbsp}mil"
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user