Reputation: 3936
I have an issue where the format returned from the exact same methods are different in different java versions.
Currency currency = Currency.getInstance("CAD");
NumberFormat formatter = NumberFormat.getCurrencyInstance();
formatter.setCurrency(currency);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
System.out.println(" " + formatter.format(10.00)) ;
It returns CA$10.00
in Java 11 but in Java 8 it's CAD10.00
.
Is there any way I can get the prefix to always be CAD across Java versions? I know that currency.getCurrencyCode()
returns CAD consistently across the versions. But I can't seem to find an overloaded method that let's me configure this.
Upvotes: 0
Views: 1978
Reputation: 20914
The following works for me. Looking through the source code, it appears that the CA$
is the currency symbol. Seems like it was changed from CAD
(in Java 8) to CA$
(in later versions). The following line of code actually returns a DecimalFormat
instance.
NumberFormat formatter = NumberFormat.getCurrencyInstance();
You can explicitly set the currency symbol to CAD
.
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Currency;
public class SchTasks {
public static void main(String args[]) {
Currency currency = Currency.getInstance("CAD");
NumberFormat formatter = NumberFormat.getCurrencyInstance();
formatter.setCurrency(currency);
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setCurrencySymbol("CAD");
((DecimalFormat) formatter).setDecimalFormatSymbols(dfs);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
System.out.println(" " + formatter.format(10.00)) ;
}
}
You can run the above code from this JDoodle
https://www.jdoodle.com/iembed/v0/s67
Upvotes: 3