0 votes
1 view
in Java by (6.8k points)

How to print a float with 2 decimal places in Java? Can I do it with System.out.print?

1 Answer

0 votes
by (13k points)

You can do it using printf method, like so:

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

In short, the %.2f syntax tells Java to return your variable with 2 decimal places in decimal representation of a floating-point number 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

Want to learn Java? Check out the Java certification from Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Oct 17, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
asked Oct 9, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !

Categories

...