How to print a float number with 2 decimal places in Scala

2 Answers

0 votes
val number: Float = 3.14159f

val formattedNumber = String.format("%.2f", number)

println(formattedNumber)



/*
run:

3.14
 
*/

 



answered Mar 3, 2025 by avibootz
0 votes
val number: Float = 3.14159f

val formattedNumber = BigDecimal(number).setScale(2, BigDecimal.RoundingMode.HALF_UP).toString

println(formattedNumber)



/*
run:

3.14
 
*/

 



answered Mar 3, 2025 by avibootz

Related questions

2 answers 185 views
3 answers 178 views
3 answers 158 views
1 answer 161 views
2 answers 149 views
3 answers 394 views
...