9

我的项目确实从厘米转换为英寸。我做到了:我怎样才能用 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");


    }
}
4

3 回答 3

11

你可以这样做:

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

如果你真的想要Math.round

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

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

于 2012-11-03T15:26:11.583 回答
8

为了使用该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 个十进制数字)。

于 2012-11-03T15:24:51.570 回答
1

您可以使用以下命令打印到小数点后两位。

 System.out.printf("%.2f inch is %.2f centimeters%n", inches, centimeters);
于 2012-11-03T17:08:37.360 回答