Announcement Announcement Module
Collapse
No announcement yet.
Property editors: Multiple number formats? Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Property editors: Multiple number formats?

    I have a JSP with several fields that hold numeric data. The type on the underlying form backing object is Double for each of the fields. The values are bound to the JSP fields using <spring:bind>.

    The problem is that I want a different number format to be used when binding depending on the field. eg some fields are money fields and should always display with 2 decimal places. Other fields are quantity and unit price fields and could have an arbitrary number of decimal places.

    If just a single display format were required for all Double values in the form, I could register an instance of CustomNumberEditor(Double.class, someNumberFormat, true) with the form controller via the initBinder() method, and the specified NumberFormat would be automatically applied to all Double fields in the form. But because the format depends on the specific field, I don't think this strategy will work.

    Any suggestions?

    Thanks in advance ...

    Steve

  • #2
    The formatting of your numbers could be done in the JSP using the JSTL taglib.

    Code:
    <%@ taglib prefix="fmt" uri="http&#58;//java.sun.com/jstl/fmt" %>
    
    <fmt&#58;formatNumber value="$&#123;amount&#125;" type="currency" currencySymbol="$"/>
    This will display the number formatted as $15.90.
    Of course there are many more possibilities for formatting.

    http://java.sun.com/products/jsp/jst...matNumber.html

    Hope this helps,
    Arjan Huijzer

    Comment


    • #3
      The DataBinder class has two registerCustomEditor methods, one that takes a class and editor, and one that takes a class, fieldname and editor.

      I have not tested this myselft, but using the latter method you should be able to set different editors to your fields, I think...

      Read the docs and test it.


      Trond

      Comment


      • #4
        The first thing I'd do is stop using Doubles.

        Double (and Float) basically suck for handling money, and should be removed from Java unless you're doing something like the calculations to land someone on the moon.

        Use BigDecimal instead which is designed for handling money.

        You can also use the setScale method in BigDecimal to handle rounding, which is useful if doing any sort of calcs since there are a bunch of round up/down, etc, variations.

        Comment

        Working...
        X