如何以文化无关模式将双精度数转换为字符串,然后再转换回来?

问题描述 投票:0回答:1

我需要将双精度浮点值(Double)转换为字符串,并以与区域性无关的格式转换回来。

Kotlin 的惯用方法是什么?

BR。

kotlin data-conversion
1个回答
0
投票
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
}
© www.soinside.com 2019 - 2024. All rights reserved.