ps0604
ps0604

Reputation: 1071

Setting number of decimals in formatting programmatically

I have the following Double in Scala:

val value: Double = 12.34

and get the formatted value, like so:

val formatted = f"$value%1.5f"

But I need to set the number of decimals (above 5) programmatically. I tried this, but it doesn't work:

val dec = 8
val formatted = f"$value%1.decf"

Any ideas?

Upvotes: 1

Views: 48

Answers (3)

ConorR
ConorR

Reputation: 487

How about

fmt="%."+n+"f"
fmt.format(12.34)

Too obvious?

Upvotes: 1

Jeffrey Chung
Jeffrey Chung

Reputation: 19507

val value: Double = 12.34
val dec = 8
val formatted = s"%1.${dec}f".format(value) // 12.34000000

Upvotes: 2

Tanjin
Tanjin

Reputation: 2452

You can use the scala BigDecimal with its setScale def then convert to a Double if necessary:

BigDecimal(12.35564126).setScale(5, BigDecimal.RoundingMode.HALF_UP).toDouble
// res0: Double = 12.35564

Upvotes: 1

Related Questions