Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Money - Smallest Unit of currency

I have a downstream service (Stripe) which requires I send currency in the smallest currency unit (zero-decimal currency in their docs). I.e. to charge $1 I would send { "currency": "USD", amount: 100 } and to charge ¥100 I would send { "currency": "YEN", amount: 100 }

My upstream applications do not want to handle the currency in this way and want to use standard currency formats. Is there a means of transforming javax.money.MonetaryAmount into a zero decimal currency format?

Or am I going to have to write the conversions manually?

like image 334
Ben Flowers Avatar asked Nov 18 '22 17:11

Ben Flowers


1 Answers

I've seen some people use BigDecimal. Here it is as a function. Please write some tests for it :) :

    public static BigDecimal currencyNoDecimalToDecimal(int amount, String currencyCode) {
        Currency currency = Currency.getInstance(currencyCode);  // ISO 4217 codes
        BigDecimal bigD = BigDecimal.valueOf(amount);
        System.out.println("bigD = " + bigD); // bigD = 100
        BigDecimal smallD = bigD.movePointLeft(currency.getDefaultFractionDigits());
        System.out.println("smallD = " + smallD); // smallD = 1.00
        return smallD;
    }

    public static void main(String[] args) {
        int amount = 100;
        String currencyCode = "USD";
    
        BigDecimal dollars = currencyNoDecimalToDecimal(amount, currencyCode);
        System.out.println("dollars = "+dollars);
    }
like image 162
shanecandoit Avatar answered Mar 04 '23 08:03

shanecandoit