弱弱的问下,JAVA 里面有没有什么方法直接把一个小数 四舍五入 转化为整数?

解决方案 »

  1.   

     (1)
    import java.text.io; 
    DecimalFormat df=new DecimalFormat("#.00"); 
    System.out.println(df.format(d1)); 
    System.out.println(df.format(d2)); (2) 
    public int getRound(double dSource)...{
    int iRound
    //BigDecimal的构造函数参数类型是double
    BigDecimal deSource = new BigDecimal(dSource);
    //deSource.setScale(0,BigDecimal.ROUND_HALF_UP) 返回值类型 BigDecimal
    //intValue() 方法将BigDecimal转化为int
    iRound= deSource.setScale(0,BigDecimal.ROUND_HALF_UP).intValue();
    return iRound;
    } 转自 http://esffor.javaeye.com/blog/96158还有就是 你要按 第几位四舍五入 
    第一位  4.5=5
    第二位 4.49=4.5
      

  2.   


    DecimalFormat df = new DecimalFormat("#.00");
    System.out.println(df.format(4.5));
    System.out.println(df.format(4.492));
    System.out.println(df.format(4.496));
    这个简便。不过返回值变成String了。
      

  3.   


    要是就这么简单,直接Math.round吧。
    System.out.println(Math.round(4.5));
    System.out.println(Math.round(4.49));
      

  4.   

    谢谢大家,受教了!!!
    CSDN 真棒!
      

  5.   

    四舍五入:Math.round
    天花板函数(向上取整):Math.floor 结果为 double,需要强转
    地板函数(向下取整):Math.cell 结果为 double,需要强转执行一下下面的代码就知道了:public class Test {    public static void main(String[] args) throws UnsupportedEncodingException {
            double[] a = { -5.3, -6.5, -0.1, 0, 0.1, 5.3, 6.5 };
            System.out.printf("%-10s %-10s %-10s %-10s%n", "Number", "round", "floor", "cell");
            System.out.println("--------------------------------------------");
            for(int i = 0; i < a.length; i++) {            
                System.out.printf("%-10f %-10d %-10f %-10f%n", a[i], Math.round(a[i]), Math.floor(a[i]), Math.ceil(a[i]));
            }
        }
    }
      

  6.   

    Number     round      floor      cell      
    --------------------------------------------
    -5.300000  -5         -6.000000  -5.000000 
    -6.500000  -6         -7.000000  -6.000000 
    -0.100000  0          -1.000000  -0.000000 
    0.000000   0          0.000000   0.000000  
    0.100000   0          0.000000   1.000000  
    5.300000   5          5.000000   6.000000  
    6.500000   7          6.000000   7.000000  
      

  7.   


    说错了。floor 是向下取整,地板函数
    cell 是向上取整,天花板函数