1. Overview
In this short tutorial, we'll see how to use dot “.” as the decimal separator when formatting numeric output in Java.
Usually, we just need to use the String.format() method as:
double d = 10.01d;
String.format("%.2f", d);
This method uses our JVM's default Locale to choose the decimal separator. For example, it would be a dot for US Locale, and for GERMANY, it would be a comma.
In case it's not a dot, we can use an overloaded version of this method where we pass in our custom Locale:
String.format(Locale.US, "%.2f", d);
We can use the format() method of a DecimalFormat object to achieve the same goal:
DecimalFormatSymbols decimalFormatSymbols = DecimalFormatSymbols.getInstance();
decimalFormatSymbols.setDecimalSeparator('.');
new DecimalFormat("0.00", decimalFormatSymbols).format(d);
We can also use the format() method of a Formatter object:
new Formatter(Locale.US).format("%.2f", d)
5. Use Locale.setDefault() Method
Of course, we can manually configure Locale for our application, but changing the default Locale is not recommended:
Locale.setDefault(Locale.US);
String.format("%.2f", d);
6. Use VM Options
Another way to configure Locale for our application is by setting the user.language and user.region VM options:
-Duser.language=en -Duser.region=US
7. Use printf() Method
If we don't need to get the value of the formatted string but just print it out, we can use the printf() method:
System.out.printf(Locale.US, "%.2f", d);
8. Conclusion
In summary, we've learned different ways to use dot “.” as the decimal separator in Java.
res – REST with Spring (eBook) (everywhere)