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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With