Search code examples
javacurrency

Converting different countrys currency to double using java


I have once scenario where in i get the currencies as a String, for eg:

$199.00

R$ 399,00

£25.00

90,83 €

AED 449.00

How do i convert these currencies to double in java?


Solution

  • Never use double for representing exact amounts

    Well, of course you can do, but you need to really understand floating point arithmetic

    Use a NumberFormat. Whilst it does handle some currencies, it's usually easier just to strip all the currency symbols. The NumberFormat will use Locale to work out the delimiters to use:

    public static BigDecimal parse(final String amount, final Locale locale) throws ParseException {
        final NumberFormat format = NumberFormat.getNumberInstance(locale);
        if (format instanceof DecimalFormat) {
            ((DecimalFormat) format).setParseBigDecimal(true);
        }
        return (BigDecimal) format.parse(amount.replaceAll("[^\\d.,]",""));
    }
    

    This takes a String of the amount and the Locale. It then creates a BigDecimal parsing NumberFormat instance. It uses replaceAll and regex to strip all but digits, . and , from the number then parses it.

    A quick demo against your examples:

    public static void main(String[] args) throws ParseException {
        final String dollarsA = "$199.00";
        final String real = "R$ 399,00";
        final String dollarsB = "£25.00";
        final String tailingEuro = "90,83 €";
        final String dollarsC = "$199.00";
        final String dirham = "AED 449.00";
    
        System.out.println(parse(dollarsA, Locale.US));
        System.out.println(parse(real, Locale.FRANCE));
        System.out.println(parse(dollarsB, Locale.US));
        System.out.println(parse(tailingEuro, Locale.FRANCE));
        System.out.println(parse(dollarsC, Locale.US));
        System.out.println(parse(dirham, Locale.US));
    }
    

    Output:

    199.00
    399.00
    25.00
    90.83
    199.00
    449.00
    

    I have simply used US where the decimal is . and FRANCE where the decimal is , but you could use the correct Locale for the currency if you wish.