How can I set a fixed number of decimal places for numerical values in Groovy? Obviously that's easy for numbers with 4 decimals and more but what about this one? Example:
def num = 2.58
return 2.5800
I would like to avoid turning those into strings.
Appreciate your help, thanks
The normal way of dealing with decimal formatting in java/groovy would be the java DecimalFormat class. The following code:
import java.text.DecimalFormat
def num = 2.58
def df = new DecimalFormat("#0.0000")
def formatted = df.format(num)
println "formatted: ${formatted}"
gives the following output when run:
─➤ groovy solution.groovy
formatted: 2.5800
─➤
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With