带格式的 Scala 字符串插值,如何更改语言环境? [英] Scala String interpolation with Format, how to change locale?

查看:55
本文介绍了带格式的 Scala 字符串插值,如何更改语言环境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在瑞典进行格式字符串插值时,在使用十进制数字创建字符串时,我得到的是逗号而不是点:

When doing format string interpolation in Sweden I get a comma instead of a dot when creating strings with decimal numbers:

scala> val a = 5.010
a: Double = 5.01

scala> val a = 5.0101
a: Double = 5.0101

scala> f"$a%.2f"
res0: String = 5,01

我的问题是,如何设置格式才能获得结果 5.01?我希望能够仅为该字符串设置语言环境,即我不会更改整个环境的语言环境.

My question is, how do I set the format so that I get the result 5.01? I would like to be able to set the locale only for that String, i.e. so that I don't change the locale for the whole environment.

干杯,

约翰

推荐答案

使用相同的 Java 库编号格式支持 可访问来自 StringOps 丰富的字符串类,您可以为该输出指定另一个语言环境:

Using the same Java library number formatting support accessible from StringOps enriched String class, you could specify another locale just for that output:

"%.2f".formatLocal(java.util.Locale.US, a)

(如如何将 Int 转换为给定长度且前导零对齐的字符串中所述?")

Scala 的方法是使用 string f interpolator (Scala 2.10+),正如在 OP 的问题中一样,但它使用当前语言环境",没有提供一种简单的方法来将该语言环境设置为不同的语言环境,仅用于一次调用.

The Scala way would be to use the string f interpolator (Scala 2.10+), as in the OP's question, but it is using the "current locale", without offering an easy way to set that locale to a different one just for one call.

这篇关于带格式的 Scala 字符串插值,如何更改语言环境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆