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 302 views
3 answers 325 views
3 answers 311 views
1 answer 262 views
2 answers 297 views
3 answers 545 views
...