3

I'm trying to compose a formatted string that should look like this:

A bottle of vodka costs x.yz rubles.

where x.yz is an arbitrary Double value rounded to 2 decimal signs.

To achieve this, I use string interpolation with printf syntax:

val cost = 2.56
val str = f"A bottle of vodka costs $cost%.2f rubles."

Unfortunately, on a machine with Russian locale, the snippet above yields a result that is a bit different from what I want to achieve:

str: String = A bottle of vodka costs 2,56 rubles.

This is understandable (the Java formatter used by f interpolator applies the locale-specific decimal separator, as outlined here), but I still want to use decimal dot instead of comma.

I'm aware of a possible workaround – using the formatLocal() method with explicitly set locale:

 val str = "A bottle of vodka costs %.2f  rubles.".formatLocal(java.util.Locale.US, cost)

but it does not strike me as a particularly Scalaesque way of doing things.

So my question is this: is it possible to format a string with a specific decimal separator using only f interpolation, without any extraneous method calls?

Voidy
  • 33
  • 5
  • 1
    Related: [*the string `f` interpolator is using the "current locale", without offering an easy way to set that locale to a different one just for one call.*](http://stackoverflow.com/questions/24780052/scala-string-interpolation-with-format-how-to-change-locale) – Wiktor Stribiżew Sep 07 '16 at 11:04
  • @WiktorStribiżew thank you! Notice, however, that my question is limited to using an arbitrary decimal separator; I'm not interested in changing locale. – Voidy Sep 07 '16 at 11:11

1 Answers1

3

At the moment f interpolator does not support locales nor custom separators (see macro_StringInterpolation_f.scala / FastTrack.scala).

dveim
  • 3,381
  • 2
  • 21
  • 31
  • From what I've gleaned from [Scala source code on GitHub](https://github.com/scala/scala), this seems true (if a tad disappointing). Thanks! – Voidy Sep 12 '16 at 06:50