Florian Baierl
Florian Baierl

Reputation: 2481

Format double with variable decimal precision

I know that for in Scala.js (cannot use java.text.DecimalFormat) I can write this:

val number = 1.2345
println(f"$x%.2f") // "1.23"

However, this doesn't seem to work:

val decimalPlaces = 2
println(f"$x%.${decimalPlaces}f")
// [error] Missing conversion operator in '%'; use %% for literal %, %n for newline      f"$x%.${decimalPlaces}f"

// also doesn't work: (f"$x%." + decimalPlaces + "f").toFloat

How can I achieve a variable decimal precision?

Upvotes: 1

Views: 536

Answers (2)

Grzegorz Oledzki
Grzegorz Oledzki

Reputation: 24251

I suppose the reason it doesn't work is that nowhere in the expression:

    s"$number%.$decimalPlacesf" # DOESN'T WORK

we are providing the order on how should the variables be resolved.

You need to artificially enforce it. Similarly to @nattyddubbs's answer:

val number = 1.2345
val decimalPlaces = 3

val format = s"%.${decimalPlaces}f"
println(format.format(number)) # 1.235

Upvotes: 0

nattyddubbs
nattyddubbs

Reputation: 2095

This works

val number = 1.2345
val decimalPlaces = 2
println(("%." + decimalPlaces + "f").format(number))

There is an implicit call to StringLike for format.

Upvotes: 2

Related Questions