Home Grails String to BigDecimal
Reply: 3

Grails String to BigDecimal

Raphael Guimarães
Raphael Guimarães Published in 2017-12-05 17:04:02Z

I can't figure out how to transform a String into a BigDecimal inside a Grails Application.

I'm doing:

person.salary = params.number

But I got a error.

*salary is a BigDecimal and params.number is always a string.
Jeff Scott Brown
Jeff Scott Brown Reply to 2017-12-05 17:20:54Z

I can't figure out how to transform a String into a BigDecimal inside a Grails Application.

BigDecimal has a String constructor so one thing you could do is new BigDecimal(params.number).

You have other options...

You could do params.number as BigDecimal.

You could use one of the type converting convenience methods like params.double('number') as BigDecimal or you could provide a default value like params.double('number', 21.12) as BigDecimal). Be aware that you could lose precision while converting to a double so if that is an issue, don't do that.

elixir Reply to 2017-12-05 17:53:35Z

You can try

person.salary = params.number.toBigDecimal()
Nic Olas
Nic Olas Reply to 2017-12-06 12:07:12Z

If you really want number parameter to be BigDecimal you can consider to the bind parameter with following method:

Method 1: Bind as Controller Action's argument
Instead of access by params.number you can add number parameter as below:

def anyAction(double number){
  person.salary = number

Method 2: Data Binding with Domain object

Create a domain

class SomeClass {
    BigDecimal number

Data binding in controller action

// will bind every parameters in params to an object dataBinding
def dataBinding = new SomeClass(params) 
person.salary = dataBinding.number // it number are BigDecimal

May be there are other way than this, but I hope it can help

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.316312 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO