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 Boolean
Java Byte
Java Character
Java Currency
Java Double
Java Enum
Java Float
Java Integer
Java Long
Java Short
Java Auto Grow Array
Java Array Compare
Java Array Convert
Java Array Copy Clone
Java Array Fill
Java Array Search and Sort
Java String Convert
Java String File
Java String Format
Java String Operation
Java BigDecimal
Java BigInteger