Round a float to the default number of decimal places in Java
Description
The following code shows how to round a float to the default number of decimal places.
Example
/* w w w .j a v a 2s . co m*/
public class Main {
/**
* Round a float to the default number of decimal places.
*/
public static float Round(float value) {
return Round(value, 2);
}
/**
* Round a float to the specified number of decimal places.
*/
public static float Round(float value, int places) {
float p = (float) Math.pow(10, places);
value = value * p;
float tmp = Math.round(value);
return (float) tmp / p;
}
public static void main(String[] argv) {
System.out.println(Round(1.234234f,3));
System.out.println(Round(1.666666f,3));
}
}
The code above generates the following result.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »