Math round java

后端 未结 3 1635
悲哀的现实
悲哀的现实 2020-12-06 17:56

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         


        
3条回答
  •  渐次进展
    2020-12-06 18:40

    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:

    1. Add this import at the beginning of your code:

      import java.text.DecimalFormat;
      
    2. 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).

提交回复
热议问题