In Java, there are a few ways to round float
or double
to 2 decimal places
import java.math.RoundingMode; public class DecimalFormat public static void main(String[] args) { double input = 2105.1234; System.out.println("salary : " + input); // DecimalFormat, default is RoundingMode.HALF_EVEN df.setRoundingMode(RoundingMode.UP); } |
Output
salary : 2105.1234 |
import java.math.BigDecimal; public class BigDecimalExample { public static void main(String[] args) { double input = 3.1123435; BigDecimal bd = new BigDecimal(input).setScale(2, RoundingMode.HALF_UP); System.out.println("salary : " + salary); } } |
Output
double : 3.1123435 |
public class MathExample { public static void main(String[] args) { double input = 1120.1235; System.out.println("salary : " + input); double salary = Math.round(input * 100.0) / 100.0; System.out.println("salary : " + salary); } } |
Output
salary : 1120.1235 |