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 174 views
3 answers 166 views
3 answers 152 views
1 answer 154 views
2 answers 145 views
3 answers 391 views
...