How to format Double with dot?

JavaStringFormatDouble

Java Problem Overview


How do I format a Double with String.format to String with a dot between the integer and decimal part?

String s = String.format("%.2f", price);

The above formats only with a comma: ",".

Java Solutions


Solution 1 - Java

String.format(String, Object ...) is using your JVM's default locale. You can use whatever locale using String.format(Locale, String, Object ...) or java.util.Formatter directly.

String s = String.format(Locale.US, "%.2f", price);

or

String s = new Formatter(Locale.US).format("%.2f", price);

or

// do this at application startup, e.g. in your main() method
Locale.setDefault(Locale.US);

// now you can use String.format(..) as you did before
String s = String.format("%.2f", price);

or

// set locale using system properties at JVM startup
java -Duser.language=en -Duser.region=US ...

Solution 2 - Java

Based on this post you can do it like this and it works for me on Android 7.0

import java.text.DecimalFormat
import java.text.DecimalFormatSymbols

DecimalFormat df = new DecimalFormat("#,##0.00");
df.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.ITALY));
System.out.println(df.format(yourNumber)); //will output 123.456,78

This way you have dot and comma based on your Locale

Answer edited and fixed thanks to Kevin van Mierlo comment

Solution 3 - Java

If it works the same as in PHP and C#, you might need to set your locale somehow. Might find something more about that in the Java Internationalization FAQ.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShikarn-OView Question on Stackoverflow
Solution 1 - JavasfusseneggerView Answer on Stackoverflow
Solution 2 - JavaUltimo_mView Answer on Stackoverflow
Solution 3 - JavaSvishView Answer on Stackoverflow