1


I need to create a Double with two decimals from a String- in other words, I need to turn "100" into 100.00.
Surprisingly:

double d = Double.valueOf("500");
DecimalFormat df = new DecimalFormat("#.00");
System.out.print(df.format(d));

Prints out:

500,00

I'd need rather "500.00". How can I fix it ?
Thanks

user2824073
  • 2,407
  • 10
  • 39
  • 73
  • 4
    That depends on your JVM locale. – meskobalazs Oct 29 '14 at 13:10
  • look into using printf for formatting output – LeatherFace Oct 29 '14 at 13:11
  • import java.text.DecimalFormat; import java.text.NumberFormat; import java.util.Locale; public class Main { public static void main(String[] args) { NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH); DecimalFormat df = (DecimalFormat)nf; df.applyPattern("#.00"); double d = Double.valueOf("500"); System.out.print(df.format(d)); } } – krystan honour Oct 29 '14 at 13:25

1 Answers1

1

You can change the separator either by setting a locale or using the DecimalFormatSymbols.

If you want the grouping separator to be a point, you can use an european locale:

NumberFormat nf = NumberFormat.getNumberInstance(Locale.GERMAN);
DecimalFormat df = (DecimalFormat)nf;

Alternatively you can use the DecimalFormatSymbols class to change the symbols that appear in the formatted numbers produced by the format method. These symbols include the decimal separator, the grouping separator, the minus sign, and the percent sign, among others:

DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(currentLocale);
otherSymbols.setDecimalSeparator(',');
otherSymbols.setGroupingSeparator('.'); 
DecimalFormat df = new DecimalFormat(formatString, otherSymbols);


Also, you might find this useful: http://tutorials.jenkov.com/java-internationalization/decimalformat.html explains almost everything related to your problem in a very simple and nice manner.

EMM
  • 1,812
  • 8
  • 36
  • 58
  • Thanks, I've already found it in the suggested duplicate, however your answer is correct. – user2824073 Oct 29 '14 at 13:21
  • Yeah, I provided that for quick reference in case you missed it, but I would recommend to take a look at the tutorial link. It looks good to me. Good day. – EMM Oct 29 '14 at 13:30