Groovy : String to float Conversion

Viewed 4811

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

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.

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()
Related