我需要将双精度浮点值(Double)转换为字符串,并以与区域性无关的格式转换回来。
Kotlin 的惯用方法是什么?
BR。
import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import java.util.*
fun doubleToString(value: Double): String {
val format = DecimalFormat("#.####################") // Pattern with precision to your liking
format.decimalFormatSymbols = DecimalFormatSymbols(Locale.US) // Ensure culture independence (e.g., dot as decimal separator)
return format.format(value)
}
fun stringToDouble(value: String): Double {
val format = DecimalFormat("#.####################") // Use the same pattern to ensure correct parsing
format.decimalFormatSymbols = DecimalFormatSymbols(Locale.US) // Consistent locale
return format.parse(value).toDouble()
}
fun main() {
val doubleValue = 12345.6789
val stringValue = doubleToString(doubleValue)
println("Double to String: $stringValue") // 12345.6789
val parsedValue = stringToDouble(stringValue)
println("String to Double: $parsedValue") // 12345.6789
}