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
{
pub
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.
You can print to two decimal places using the following.
System.out.printf("%.2f inch is %.2f centimeters%n", inches, centimeters);
In order to use the Math.round
method you need to change only one line in your code:
double inches = Math.round(centimeters / 2.54);
If you want to keep 2 decimal digits you can use this:
double inches = Math.round( (centimeters / 2.54) * 100.0 ) / 100.0;
By the way I suggest you a better way to deal with these problems without rounding.
Your problem is only about displaying, so you don't need to change the model of the data, you can just change its display. To print the numbers in the format you need, you can let all your logic code like this and print the result in the following way:
Add this import at the beginning of your code:
import java.text.DecimalFormat;
Print the output in this way:
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(inches) + " Inch Is " +
df.format(centimeters) + " centimeters");
The string "#.##"
is the way your number will be displayed (in this example with 2 decimal digits).