60

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: ",".

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Shikarn-O
  • 3,337
  • 7
  • 26
  • 27

3 Answers3

146

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 ...
sfussenegger
  • 35,575
  • 15
  • 95
  • 119
  • 2
    Adding to the list: (new DecimalFormat("0.##", new DecimalFormatSymbols(Locale.US))).format(price); – user1154664 Apr 07 '13 at 20:47
  • Note that the 2nd approach (Formatter.format) returns the Formatter itself. One needs to instantize the Formatter with a object where to put the output to for it to work (https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#format-java.lang.String-java.lang.Object...-) – dCSeven Jul 16 '20 at 08:32
1

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

Ultimo_m
  • 4,724
  • 4
  • 38
  • 60
  • There's a problem here: if the numer is **0.0** , the result is **,00**, instead of **0,00** : how can be fixed? ps: there's a typo in `df.setDecimalFormatSymbols(` , misses un L `Symbos` – Leviand Jul 12 '18 at 16:05
  • @Leviand you are right, I don't know why that happens. I would suggest to create a kotlin extension and set a condition when number is 0 – Ultimo_m Jul 16 '18 at 13:35
  • # means possible number, but left away if it's not there. Hence 0 would result in this. To fix this use "#,##0.00". See the third 0. That means that number will always be filled. – Kevin van Mierlo Sep 12 '18 at 12:21
  • @KevinvanMierlo I tested it and you're right, I will edit the answer. Thanks – Ultimo_m Sep 12 '18 at 12:53
-2

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.

Svish
  • 152,914
  • 173
  • 462
  • 620