4

I want to store several money values in a grails 2.0 application using BigDecimal.

I have a domain class with a BigDecimal field

Invoice {
     BigDecimal amount 
}

The GSP input form field looks like the next code snippet

<div class="fieldcontain ${hasErrors(bean: invoiceInstance, field: 'amount', 'error')} required">

    <label for="amount">
        <g:message code="invoiceInstance.amount.label" default="Amount" />
        <span class="required-indicator">*</span>
    </label>
    <g:field type="number" name="amount" required="" value="${invoiceInstance.amount}"/>
</div>

If I work in English locale everything works fine. The user enters 100 in the field and when the value is submitted 100.00 is sent to the server. The controller parsing looks like this :

invoiceInstance.properties = params

and the BigDecimal amount of 100.00 for a English locale is 100 € as expected

The problem is that if the user changes the locale to spanish and enters 100 in the field. The string 100.00 is sent to the server but the parsing sets amount to 10000 because it understand the the decimal separator for spanish number is , and . is the thousand separator.

How can I avoid this problem?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Sergio del Amo
  • 76,835
  • 68
  • 152
  • 179

2 Answers2

0

It's been a few years but the same thing still happens in Grails 4.1.1. You can avoid this issue by binding the field value explicitly, e.g.:

invoiceInstance.amount = new BigDecimal(params['amount'] as String)
feuernurmitm
  • 312
  • 2
  • 11
0

You might need to check the user's locale before parsing the value by inspecting the Accept-Language header. Rather than naively constructing from params, you would probably create a new BigDecimal with the value passed in the Locale referenced by the header.

Community
  • 1
  • 1