Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy : String to float Conversion

Used code below to save value for float

domainInstance.standardScore = params["standardScore"] as float

In this case my input was given as 17.9 and in db2 database saving as 17.899999618530273 but I want to save as 17.9 itself, let me know how to do it

like image 941
user2529774 Avatar asked Nov 19 '25 07:11

user2529774


2 Answers

You can't set precision to a Float or Double in Java. You need to use BigDecimal.

domainInstance.standardScore = new BigDecimal(params["standardScore"]).setScale(1, BigDecimal.ROUND_HALF_UP);

The method BigDecimal.setScale(1, ...) limits decimal to one place only. The second parameter is the rounding strategy.

like image 129
Raphael Avatar answered Nov 21 '25 02:11

Raphael


You need to use BigDecimal to do Conversion from String, then BigDecimal(value).floatValue() to get float, You can do this on more that one way, examples

1 - Using setScale in BigDecimal

   def temp = new BigDecimal(params["standardScore"]).setScale(1, BigDecimal.ROUND_HALF_UP)

2- Using DecimalFormat

    DecimalFormat df = new DecimalFormat("#.0");
    def temp =  new BigDecimal(df.format(params["standardScore"] ))

Then you need to get the float value

domainInstance.standardScore = temp.floatValue()
like image 45
Ahmad Al-Kurdi Avatar answered Nov 21 '25 04:11

Ahmad Al-Kurdi



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!