Java – Round Double To Two Decimal Places

Round a double value to a given number of decimal places.

double longNumber = 25.3713789;

// TWO DECIMAL PLACES
DecimalFormat df = new DecimalFormat(“0.0#”);
String roundedNumber = df.format(longNumber);
System.out.println(roundedNumber);

// THREE DECIMAL PLACES
df = new DecimalFormat(“0.00#”);
roundedNumber = df.format(longNumber);
System.out.println(roundedNumber);

 

Advertisements

How To Convert A Float Value to An Integer

JAVA – how to convert a float value to an interger.

Example 1:

float a = 110.25;
int a = (int)(a + 0.5f);

int a will be rounded down version of float a. The value will be 110.

Example 2:

float b = 110.75;
int b = (int)(b + 0.5f);

int b will be rounded up version of float b. The value will be 111.