To format monetary values, a good alternative is to use NumberFormat
. Ex:
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
System.out.println(formatter.format(123456.78)); // R$ 123.456,78
I use a Locale
(in the above example I used pt_BR
, which is equivalent to Brazilian Portuguese), as it controls some aspects of formatting, such as the characters used to separate thousands and decimal places, in addition to the prefix "R$". If you use for example Locale.US
- American English, the result will be $123,456.78
(and call themselves getCurrencyInstance()
no parameters, is used the default locale which is configured in the JVM, so I recommend using a locale specific not to depend on these settings, which may even change in Runtime without you noticing).
With NumberFormat
you can control other aspects, such as the option not to include the point to separate the thousands, change the amount of decimals and even the rounding mode. Some examples:
double valor = 123456.78987;
NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("pt", "BR"));
System.out.println(formatter.format(valor)); // R$ 123.456,79
formatter.setGroupingUsed(false); // não separar os milhares
System.out.println(formatter.format(valor)); // R$ 123456,79
formatter.setRoundingMode(RoundingMode.DOWN); // arredondar sempre para baixo
System.out.println(formatter.format(valor)); // R$ 123456,78
// mudar a quantidade de casas decimais
formatter.setMaximumFractionDigits(3);
System.out.println(formatter.format(valor)); // R$ 123456,789
See the documentation for more details.
If you don’t want to print the currency symbol and just want to format the number, then just use DecimalFormat
, as already suggested the another answer. It also has the same methods to control the number of decimals, etc., but by default does not print the currency code (R$) - although it is also possible:
// \u00A4 corresponde ao código da moeda
DecimalFormat df = new DecimalFormat("\u00A4 #,##0.00");
df.setCurrency(Currency.getInstance("BRL")); // BRL = código do Real
System.out.println(df.format(valor)); // R$ 123.456,79
The currency code passed to Currency.getInstance
is based on ISO 4217. In case I used BRL
, which is equivalent to the Real.
Another detail is that if you’re working with monetary values, maybe double
is not the best option. Learn more by reading here and here