Reputation: 1071
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
Reputation: 19507
val value: Double = 12.34
val dec = 8
val formatted = s"%1.${dec}f".format(value) // 12.34000000
Upvotes: 2
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