kotlin 在德国使用英语时货币格式出现意外行为

2vuwiymt  于 2023-02-24  发布在  Kotlin
关注(0)|答案(1)|浏览(151)

我使用NumberFormat.getCurrencyInstance(Locale locale)来呈现价格值。据我所知,locale的国家定义了货币,而locale的语言定义了要呈现的样式。但是当使用Locale(“en”,“DE”)时,它的工作方式不同,如下面的测试所示:

@ParameterizedTest
    @CsvSource(
        value = [
            "de; DE; 1,23 €",
            "de; GB; 1,23 £",
            "en; GB; £1.23",
            "en; DE; €1.23", // <- fails because result is "1,23 €"
        ],
        delimiter = ';',
    )
    fun `formatting`(givenLanguage: String, givenCountry: String, expectedResult: String) {
        assertEquals(
            expectedResult,
            NumberFormat.getCurrencyInstance(Locale(givenLanguage, givenCountry)).format(1.23)
        )
    }

基于currencyCode对所有内容进行格式设置,工作正常

val nf = NumberFormat.getCurrencyInstance(Locale("en")) // no country "DE"
nf.currency = Currency.getInstance("EUR")
println(nf.format(1.23))
// => €1.23

但在此处添加国家“de”会导致相同的问题

val nf = NumberFormat.getCurrencyInstance(Locale("en", "DE"))
nf.currency = Currency.getInstance("EUR")
println(nf.format(1.23))
// => 1,23 €

有人能解释一下吗?

xdnvmnnf

xdnvmnnf1#

我提出的解决方案是永远不要将国家传递给NumberFormat.getCurrencyInstance(Locale locale)的Locale-argument,而是从国家中提取货币,并直接在NumberFormat示例中定义它,这非常笨拙。
实际上我是这样做的:

val nf = NumberFormat.getCurrencyInstance(Locale("en"))
nf.currency = Currency.getInstance(Currency.getInstance(Locale("", "DE")).currencyCode)
println(nf.format(1.23))
// €1.23

旁注:
在某些情况下,格式化使用货币代码,而不是符号。例如,西班牙语中的英镑(language="es"country="GB")被格式化为1,23 GBP而不是1,23 £。因此,如果有人想总是使用货币符号,我建议总是用currencySymbol替换currencyCode

println(nf.format(1.23).replace(nf.currency.currencyCode, nf.currency.symbol))
// 1,23 £

相关问题