Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a float with 2 decimal places in Java?

Can I do it with System.out.print?

like image 760
via_point Avatar asked Mar 29 '10 14:03

via_point


People also ask

How do you show float to 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do you do 2 decimal places in Java?

format(“%. 2f”) We also can use String formater %2f to round the double to 2 decimal places.

Can float have decimals Java?

Float and double are two of the data types used to represent decimal values or floating point literals in the Java programming language. Floats can represent decimal values up to 7 digits of precision, and double can represent decimal values up to 16 digits of precision.


2 Answers

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
like image 174
Anthony Forloney Avatar answered Sep 19 '22 06:09

Anthony Forloney


You can use DecimalFormat. One way to use it:

DecimalFormat df = new DecimalFormat(); 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.

like image 38
Bozho Avatar answered Sep 22 '22 06:09

Bozho