Decimal places when using Println in Java

Asked

Viewed 2,192 times

4

I have the following problem when I have this function printed

System.out.println("Area do Tetraedro =  " + c1.getArea());

the value of it is very great, example:

Tetraedo area = 389.71143170299734

How to leave it with two decimal places? And also, how to put the unit of measure at the end?

  • I don’t understand the part where you talk about unit of measure, could explain what you need?

  • in the end would have to leave so look

  • Area of Tetraedo = 389.71 Kg

  • area in kilograms?

  • it was an example but I already solved here it was worth

  • Area of a 3D object, and in kg... :-)

Show 1 more comment

2 answers

6

You can use the printf() instead of println(). Example:

System.out.printf("Area do Tetraedro =  %.2f\n", c1.getArea());

Where %.2f that the second argument of the method, i.e., the first after the string, will be represented as a floating point number limited to show only two decimal places.

The \n does the role of breaking the line, which made the println() and that the printf() does not automatically.

  • The updated version of the language points to %.2f as a syntax error, to work I changed the point by the comma.

0


You already solved, but could use the class DecimalFormat package java.text. She has the method format() which receives a decimal and formats as you wish.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.