To format a number with two decimal places in Java, you can use the DecimalFormat class of the java.text package.
Here's an example of how to use the DecimalFormat class to format a number with two decimal places:
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
double number = 123.4567;
// Create a DecimalFormat object with two decimal places
DecimalFormat df = new DecimalFormat("#.00");
// Format the number with two decimal places
String formattedNumber = df.format(number);
System.out.println(formattedNumber); // prints "123.46"
}
}Source:www.lautturi.comThis code creates a DecimalFormat object with a pattern that specifies two decimal places (.00). The format() method of the DecimalFormat object is then used to format the number with two decimal places.
You can use a similar approach to format a number with any number of decimal places, by specifying the appropriate pattern. For example, to format a number with three decimal places, you can use the pattern ".000".