-1

I would like to convert my final double value i.e ( 1.0 ) to be printed out like $1.00. How is this possible in Java?

I imported java.lang.* DecimalFormat formatter = new DecimalFormat("#.00");

Not sure how to get the dollar sign in there. I didn't know if there was any other way to do this aside from going "$" + .....

CuriousFellow
  • 225
  • 1
  • 3
  • 14

4 Answers4

0

Use String.format:

// Format double with 2 decimal places and add a dollar sign
String price = "$" + String.format("%.2f", myDouble);

To print it directly, use PrintWriter.printf, e.g. on System.out:

System.out.printf("$%.2f", myDouble);
Tobias
  • 7,723
  • 1
  • 27
  • 44
  • 1
    Honestly, printf or NumberFormat is a more direct solution, ignoring that this question is a dup. – Brian Roach Jan 19 '14 at 10:19
  • @BrianRoach Yes, thought about using `printf` first but changed it to `String.format` because it allows to use the value instead of just printing it. And, well, you *can* use `NumberFormat`, but I personally prefer simplicity. Thanks for your feedback :) – Tobias Jan 19 '14 at 10:28
0

Use DecimalFormat

    double value = 1.0;
    DecimalFormat dformat = new DecimalFormat("#.00");
    String modifiedVal = dformat.format(value);
    System.out.println("$"+modifiedVal);
gowtham
  • 977
  • 7
  • 15
0

The NumberFormat class has a pre-defined instance for currency formatting.

double value = 1.0;
NumberFormat nf = NumberFormat.getCurrencyInstance();
System.out.println(nf.format(value));
PakkuDon
  • 1,627
  • 4
  • 22
  • 21
0

You can make use of Locale & NumberFormat classes in Java.

NumberFormat formatter = NumberFormat.getCurrencyInstance(new Locale("en","US"));
System.out.println(formatter.format(1.0));
Keerthivasan
  • 12,760
  • 2
  • 32
  • 53