Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixed decimal places / Java Groovy

Tags:

decimal

groovy

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

like image 825
User763733p Avatar asked Jul 28 '26 08:07

User763733p


1 Answers

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

─➤ 
like image 141
Matias Bjarland Avatar answered Jul 30 '26 08:07

Matias Bjarland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!