NumberFormat
class from java.text
package can be used to format numbers. This class provides setMaximumFractionDigits
method which can be used to round to 2 decimal places.
package com.techstackjournal;
import java.text.NumberFormat;
public class RoundDecimals {
public static void main(String[] args) {
double total = 123.429;
NumberFormat numberFormat = NumberFormat.getInstance();
numberFormat.setMaximumFractionDigits(2);
System.out.println(numberFormat.format(total));
}
}
Output:
123.43