14

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

Johan S
  • 3,531
  • 6
  • 35
  • 63

2 Answers2

18

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.

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
4
Locale.setDefault(Locale.US)
println(f"$a%.2f")
botkop
  • 934
  • 1
  • 8
  • 17
  • 2
    Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – shkaper Sep 09 '19 at 17:10