how to get 2 decimal places in java

‮www‬.lautturi.com
how to get 2 decimal places in java

To get a number with 2 decimal places in Java, you can use the DecimalFormat class from the java.text package.

Here's an example of how to get a number with 2 decimal places in Java:

double number = 123.4567;

DecimalFormat df = new DecimalFormat("#.00");
String formattedNumber = df.format(number);

System.out.println(formattedNumber); // 123.46

In the above example, a DecimalFormat object is created using the DecimalFormat() constructor, and the format string "#.00" is passed as an argument. This format string specifies that the number should be formatted with 2 decimal places.

The format() method of the DecimalFormat object is then used to format the number, and the resulting String is stored in the formattedNumber variable.

For example, the formattedNumber variable might contain a value like "123.46".

You can also use the DecimalFormat class to format numbers with other decimal places, by modifying the format string. For example, to format a number with 4 decimal places, you can use the format string "#.0000".

For more information on formatting numbers in Java, you can refer to the documentation for the DecimalFormat class in the Java API.

Created Time:2017-11-01 20:42:53  Author:lautturi