数学圆java

我有项目做从cm转换为英寸。 我做到了:我怎么能用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"); } } 

你可以这样做:

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

如果你真的想要Math.round

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

使用1000可以有3个小数位,使用10000等可以有4个10000 。我个人更喜欢第一个选项。

要使用Math.round方法,您只需要更改代码中的一行:

 double inches = Math.round(centimeters / 2.54); 

如果你想保留2位小数,你可以使用:

 double inches = Math.round( (centimeters / 2.54) * 100.0 ) / 100.0; 

顺便提一下,我建议你一个更好的方法来处理这些问题,而不是四舍五入。

您的问题仅与显示有关,因此您无需更改数据模型,只需更改其显示即可。 要以您需要的格式打印数字,您可以让所有逻辑代码都这样,并按以下方式打印结果:

  1. 在代码的开头添加此导入:

     import java.text.DecimalFormat; 
  2. 以这种方式打印输出:

     DecimalFormat df = new DecimalFormat("#.##"); System.out.println(df.format(inches) + " Inch Is " + df.format(centimeters) + " centimeters"); 

字符串"#.##"是您的号码显示方式(在此示例中为2位小数)。

您可以使用以下方法打印到两位小数。

  System.out.printf("%.2f inch is %.2f centimeters%n", inches, centimeters);