How to Match Currency Symbols in Java

How to Match Currency Symbols in Java

How to Match Currency Symbols in Java

Handling currency symbols correctly is crucial for financial applications. In this guide, we’ll explore two effective methods to validate and match currency symbols in Java using regular expressions and locale-aware parsing.

Why Currency Symbol Matching Matters

Financial applications often require strict validation of monetary inputs. Whether you’re processing user payments or generating reports, ensuring currency symbols like $, €, or £ are correctly formatted prevents errors and maintains data integrity.

Method 1: Using Regular Expressions

Regular expressions give you precise control over input formats. Let’s create a pattern to validate US dollar amounts:

private static final String DOLLAR_PATTERN = "^$d+(.d{1,2})?$";

boolean matchesDollarAmount(String input) {

return Pattern.matches(DOLLAR_PATTERN, input);
}

Pattern Breakdown:

  • ^ and $: Anchors to ensure the entire string matches
  • $: Matches the literal dollar sign
  • d+: One or more digits
  • (.d{1,2})?: Optional decimal with 1-2 digits

Why Anchors Matter

Without anchors, patterns like $d+ might incorrectly match substrings. For example, $$34.00 would pass if using Matcher.find() instead of Pattern.matches().

Testing the Pattern

@Test
void whenValidDollarAmount_thenMatches() {

assertTrue(matchesDollarAmount("$100"));

assertTrue(matchesDollarAmount("$100.00"));

assertTrue(matchesDollarAmount("$0.99"));
}

@Test
void whenInvalidDollarAmount_thenDoesNotMatch() {

assertFalse(matchesDollarAmount("$$$34.00"));

assertFalse(matchesDollarAmount("$10.123"));
}

Method 2: Using NumberFormat

For locale-aware parsing, NumberFormat is ideal. It automatically adapts to regional settings:

NumberFormat format = NumberFormat.getCurrencyInstance(Locale.US);
try {

Number number = format.parse("$100.00");

System.out.println(number.doubleValue());
} catch (ParseException e) {

e.printStackTrace();
}

This approach handles symbols like € or £ based on the specified locale and gracefully rejects invalid formats.

Extending Patterns for Thousands

To support commas in large numbers:

private static final String DOLLAR_WITH_COMMAS_PATTERN

= "^$d{1,3}(,d{3})*(.d{1,2})?$";

This accepts inputs like $1,000.00 and $1,234,567.89.

Conclusion

Matching currency symbols in Java requires balancing strict validation with locale flexibility. Use regex for fixed formats and NumberFormat for dynamic, locale-aware parsing. Test thoroughly to avoid edge cases.

Try It Out: Experiment with the examples in your IDE or download our Java Currency Validation eBook for advanced patterns and real-world use cases.