NumberFormat.getCurrencyInstance (); failure

I am trying to parse my currency string into bigdecimal using NumberFormat.getCurrencyInstance ();

The following scenario
$1,000.01 Pass
1000.01 Pass
1,000.01 Fail -> This needs to be parsed to 1000.01 in order to pass.
abc Fail -> correct behavior. 

      

My method

   public BigDecimal parseClient(Field field, String clientValue, String message) throws ValidationException {
        if (clientValue == null) {
            return null;
        }

        NumberFormat nf = NumberFormat.getCurrencyInstance();
        try {
            return new BigDecimal(nf.parse(clientValue).toString());
        } catch (ParseException ex) {
            throw new ValidationException(message);
        }
    }

      

Does anyone know of a good solution for this to work fine?

+3


source to share


2 answers


That's pretty brute force, but why not just check for the presence of currency symbols at the beginning of the line, and if it's not there, add it?

if ( !clientValue.startsWith( "$" ) )
{
   clientValue = "$" + clientValue;
}

      



If a brute force approach is not needed, the next approach would be to pay attention to every format that a client can go into this method. Then create as many DecimcalFormat instances as needed to process the incoming input formats and allow them to be parsed.

Another approach is to standardize the incoming clientValue into a single format. This can be done with string manipulation and regular expressions. However, you still have the problem that you need to know all the different ways to enter an incoming client value into this method. Therefore, the requirements are very important here.

+1


source


Try using this constructor instead:



public static NumberFormat getCurrencyInstance(Locale inLocale)

      

+1


source







All Articles