Scala String interpolation with Format, how to change locale?

后端 未结 2 639
情书的邮戳
情书的邮戳 2021-02-19 17:55

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         


        
相关标签:
2条回答
  • 2021-02-19 18:42

    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.

    0 讨论(0)
  • 2021-02-19 18:42
    Locale.setDefault(Locale.US)
    println(f"$a%.2f")
    
    0 讨论(0)
提交回复
热议问题