via_point via_point - 1 year ago 96
Java Question

How to display an output of float data with 2 decimal places in Java?

Can I do it with


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download