数学圆java

Ale*_*lex 9 java math rounding

我的项目确实从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");


    }
}
Run Code Online (Sandbox Code Playgroud)

ars*_*jii 11

你可以这样做:

Double.valueOf(new DecimalFormat("#.##").format(
                                           centimeters)));  // 2 decimal-places
Run Code Online (Sandbox Code Playgroud)

如果你真的想要Math.round:

(double)Math.round(centimeters * 100) / 100  // 2 decimal-places
Run Code Online (Sandbox Code Playgroud)

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


enr*_*cis 8

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

double inches = Math.round(centimeters / 2.54);
Run Code Online (Sandbox Code Playgroud)

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

double inches = Math.round( (centimeters / 2.54) * 100.0 ) / 100.0;
Run Code Online (Sandbox Code Playgroud)

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

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

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

    import java.text.DecimalFormat;
    
    Run Code Online (Sandbox Code Playgroud)
  2. 以这种方式打印输出:

    DecimalFormat df = new DecimalFormat("#.##");
    System.out.println(df.format(inches) + " Inch Is " +
                       df.format(centimeters) + " centimeters");
    
    Run Code Online (Sandbox Code Playgroud)

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