Scala String interpolation with Format, how to change locale?

我的未来我决定 提交于 2019-12-05 14:30:39

问题


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

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.

Cheers,

Johan


回答1:


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)

(as described in "How to convert an Int to a String of a given length with leading zeros to align?")

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.




回答2:


Locale.setDefault(Locale.US)
println(f"$a%.2f")


来源:https://stackoverflow.com/questions/24780052/scala-string-interpolation-with-format-how-to-change-locale

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!