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");
}
}
DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With