views:

647

answers:

5

Can I do it with System.out.print? Thank you.

+9  A: 

You can use DecimalFormat. One way to use it:

DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));

Another one is to construct it using the #.## format.

I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.

Bozho
What happened with the `System.out.printf("%.2f", value)` syntax? Is it still around?
Anthony Forloney
it is. it's still an option - you can undelete your answer ;)
Bozho
Looks like it's my option, as I don't know how to use DecimalFormat yet :) Thanks!
via_point
@Bozho: I haven't done extensive Java work in a while, and when I kept seeing `DecimalFormat` answers I immediately had thought I was wrong, but thank you for clarifying that.
Anthony Forloney
+11  A: 

You can use the printf method, like so:

System.out.printf("%.2f", val);

In short, the %.2f syntax tells Java to return your variable (val) with 2 decimal places (.2) in decimal representation of a floating-point number (f) from the start of the format specifier (%).

There are other conversion characters you can use besides f:

  • d: decimal integer
  • o: octal integer
  • e: floating-point in scientific notation

You can see some examples at Learning Java - Chapter 5

Anthony Forloney
+8  A: 
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
Kevin Sylvestre
+3  A: 

Look at DecimalFormat

Here is an example from the tutorial:

  DecimalFormat myFormatter = new DecimalFormat(pattern);
  String output = myFormatter.format(value);
  System.out.println(value + "  " + pattern + "  " + output);

If you choose a pattern like "###.##", you will get two decimal places, and I think that the values are rounded up. You will want to look at the link to get the exact format you want (e.g., whether you want trailing zeros)

Uri
+4  A: 

Many people have mentioned DecimalFormat. But you can also use printf if you have a recent version of Java:

System.out.printf("%1.2f", 3.14159D);

See the docs on the Formatter for more information about the printf format string.

Mr. Shiny and New