Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Math round java

I got project do convert from cm to inch. I did it: how can i round my number with Math.round?

import java.util.Scanner;  

public class Centimer_Inch
{

public static void main (String[] args)
{
        // 2.54cm is 1 inch
       Scanner cm = new Scanner(System.in); //Get INPUT from pc-Keyboard
       System.out.println("Enter the CM:"); // Write input
       //double
       double centimeters = cm.nextDouble();
       double inches = centimeters/2.54;
       System.out.println(inches + " Inch Is " + centimeters + " centimeters");


    }
}
like image 429
Alex Avatar asked Nov 03 '12 15:11

Alex


People also ask

How do you round to 2 decimal places in Java with Math round?

DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.

Does Java round 0.5 up or down?

In mathematics, if the fractional part of the argument is greater than 0.5, it is rounded to the next highest integer. If it is less than 0.5, the argument is rounded to the next lowest integer.

How do you round to 2 decimal places in Math?

Or, if you want to round 0.2345 to two decimal places, you need to round 23.45 (0.2345*100), then divide the result (23) by 100 to get 0.23.


1 Answers

You could do something like this:

Double.valueOf(new DecimalFormat("#.##").format(
                                           centimeters)));  // 2 decimal-places

If you really wanted Math.round:

(double)Math.round(centimeters * 100) / 100  // 2 decimal-places

You can have 3 decimal places by using 1000, 4 by using 10000 etc. I personally like the first option more.

like image 189
arshajii Avatar answered Oct 01 '22 17:10

arshajii