Code Junkie
Code Junkie

Reputation: 7788

NumberFormat.getCurrencyInstance(); Failure

I'm trying to parse my currency string into a 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);
        }
    }

Anybody know of a good solution to get this to work properly?

Upvotes: 3

Views: 932

Answers (2)

mightyrick
mightyrick

Reputation: 910

It is fairly brute force, but why not just check for the presence of the currency characters at the beginning of the string, and if it is not there, prepend it?

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

If the brute force approach is not desired, the next approach would be to take note of each format that the client can come into the method. Then, create as many DecimcalFormat instances that are necessary to handle those incoming input formats -- and allow them to be parsed.

Another approach is to standardize the incoming clientValue into a single format. This could be done through string manipulation and regex. However, you still have the issue that you need to know all of the different ways the incoming clientvalue can come into the method. So requirements are very important here.

Upvotes: 1

user2030471
user2030471

Reputation:

Try using this constructor instead:

public static NumberFormat getCurrencyInstance(Locale inLocale)

Upvotes: 1

Related Questions