Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala String interpolation with Format, how to change locale?

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

like image 835
Johan S Avatar asked Jul 16 '14 11:07

Johan S


People also ask

How can you format a string in Scala?

In Scala Formatting of strings can be done utilizing two methods namely format() method and formatted() method. These methods have been approached from the Trait named StringLike.

What is string interpolation in Scala?

Starting in Scala 2.10. 0, Scala offers a new mechanism to create strings from your data: String Interpolation. String Interpolation allows users to embed variable references directly in processed string literals.

How do you do interpolation strings?

Structure of an interpolated string. To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal. To concatenate multiple interpolated strings, add the $ special character to each string literal.

Why is s used in Scala?

According to the official Scala string interpolation documentation, when you precede your string with the letter s , you're creating a processed string literal. This example uses the “ s string interpolator,” which lets you embed variables inside a string, where they're replaced by their values.


2 Answers

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.

like image 168
VonC Avatar answered Sep 21 '22 15:09

VonC


Locale.setDefault(Locale.US)
println(f"$a%.2f")
like image 25
botkop Avatar answered Sep 22 '22 15:09

botkop