Math round java

后端 未结 3 1626
悲哀的现实
悲哀的现实 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:18

    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.

    0 讨论(0)
  • 2020-12-06 18:25

    You can print to two decimal places using the following.

     System.out.printf("%.2f inch is %.2f centimeters%n", inches, centimeters);
    
    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题