how to round in java code example

Example 1: specify decimal places java

double test = 12.15;
DecimalFormat df = new DecimalFormat("#.0");
System.out.println(df.format(test)); // Console: 12.2
// # - prints a digit if provided, nothing otherwise
// . - indicates where to put the decimal seperator
// 0 - prints a digit if provided, 0 otherwise

Example 2: how to round up in java

int x = 3.14;

Math.round(x);
//Rounds to nearest int
Math.ceil(x);
//Rounds up to int
Math.floor(x);
//Rounds down to int

Tags:

Java Example