Search code examples
grailsgsp

Showing float numbers Grails in gsp


I want to manipulate float numbers in gsp, here is what i want:

If the number has a 1.* i want it to show the dot, but if it ends with zero i dont want it to show the dot and zero.

like this:

Score: 1.5

Score: 1

Score: 2.1

Score: 3

The score variable is a float number and it is an input field on the gsp that loads the number and it can be changed.

But the real problem is, how can i see if the number has decimals?


Solution

  • There is already a taglib for formating numbers: (g:formatNumber)

    I think something like this should work:

    <g:formatNumber number="${score}" type="number" format="###.##"/>
    

    But...if that doesn't work...

    I would say write your own custom taglib. If it is something that is going to be used multiple times, why loop through a list of objects in your controller, change the float to a string just to display it? Let the page decide how to show it in the proper context.

    Or

    Add a transient field to the domain object (String scoreDisplay) and then have getScoreDisplay() return the value of score as a string, formatted how you want.