Java double type round numbers

Introduction

Math.floor() can be used to round values to the nearest integer-e.g.,

y = Math.floor(x + 0.5); 

will round the number x to the nearest integer and assign the result to y.

To round numbers to specific decimal places, use a statement like

y = Math.floor(x * 10 + 0.5) / 10; 

which rounds x to the tenths position (i.e., the first position to the right of the decimal point), or

y = Math.floor(x * 100 + 0.5) / 100; 

which rounds x to the hundredths position (i.e., the second position to the right of the decimal point).


 
public class Main {
  public static void main(String[] args) {
    double x = 12.456;
    double y = Math.floor(x + 0.5);
    //from  w  w  w . ja  v a2  s . co  m
    System.out.println(y);
    
    y = Math.floor(x * 10 + 0.5) / 10; 
    System.out.println(y);
    
    y = Math.floor(x * 100 + 0.5) / 100; 
    System.out.println(y);
  }
}



PreviousNext

Related