Search code examples
javacurrency

check if currency has valid symbol


I have a string that represents a currency value like $200, €200, ¥200.

As per my task, I support the only the dollar, euro, and yen, but not other currency symbols.

I want to get the first character of string and check if that is a valid currency symbol, which means is that is either Euro or Dollar or Yen but not other currencies. How can do this in Java?

This is my sample code:

char c = s.charAt(0);

if(c == dollar || c == euro || c == yen) { // how can I write the symbols in my code?
   valid = true;
} else {
   valid = false;
}

Solution

  • It's easier than you might think:

    if(c == '$' || c == '€' || c == '¥')
    

    You say you don't want to use "special symbols" in your code... I don't understand why you wouldn't; but you can write the euro and Yen symbols as '\u20AC' and '\u00A5' respectively if you want (but note that the first thing the Java compiler does is to convert them back to and ¥....)

    A strong reason to use the unicode symbol rather than \uNNNN is readability: it would be easy to accidentally get the code wrong, and it wouldn't be easy to spot. And, presumably, you're going to write tests for the code - what do you use in the tests to make sure it's doing the right thing? If you use the \uNNNN form, you run the risk that you've got it wrong there as well; and if you use the symbol in the tests, then you may as well just use the symbol in the production code as well.