大家在平时的工作中,四舍五入的问题(金融等行业对这个要求挺高的),大家都是怎么处理?欢迎各位指教!

解决方案 »

  1.   

    需既然要求高,又怎么能舍入呢?我看一些银行的项目中都是用的BigDecimal
      

  2.   

    是的,我听别人说是用BigDecimal。但是不舍入,又该怎么处理。
      

  3.   

    int i ;
    double d = 5.6;
    取证之后--> i = (int)(5.6+0.5);
      

  4.   

    lz的意思是累加误差吧?
    如果你用数据库,可以定义decimal或money类型,
    要不然自定义一个类,小数和整数部分分别存储
      

  5.   

    Math中的round就是这么处理的,不是我要四舍五入,是在工作中碰到这种情况应该怎么处理?
    比方说我有一个数,我用两种方式都得到了,最后他们应该是一样的,但是由于在计算的过程中有四舍五入,所以导致后面两个结果就不一样了!
      

  6.   

    呵呵,Math中的round方法就是这么处理的!
      

  7.   

    round
    public static long round(double a)
    Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of the result, and casting the result to type long. In other words, the result is equal to the value of the expression: (long)Math.floor(a + 0.5d)
    Special cases: 
      

  8.   

    小数转换成整数,再缩小就是了
    [code=Java]
          double a=1.354;
          a=Math.rint(a*100)/100;
    code]
      

  9.   

    不改变单位,可以考虑,保存的时候直接存整数和小数位数

    12.58 保存 1258 2
    52.876 保存 52875 3
    计算时,采用小数位数最大的作为基准,如上面的3
    然后 小数位数比它小的,不断地乘10,如
    int a = 1258;
    for (int i=2; i<=3; i++) {a*=10;}
    然后进行加减乘除相关处理,如
    int b = 52876
    double r = a + b; 
    如果是结果是直接保存的,可以保存 r 3
    如果是要返回的,可以
    for (int i=3; i>0; i--) {
        double /= 10;
    }
    然后根据实际需要保留小数的位数进行四舍五入
      

  10.   

    定义这样相关的一个类也挺简单,如
    class Money {
        int intValue;
        int pointPos;
        public Money(double money) {
            pointPos = String.valueOf(money).lastIndex(".");
            intValue = (int)(money * Math.pow(10, pointPos));
        }
    }
      

  11.   

    有点小失物
    String s = String.valueOf(money);
    pointPos = s.length()-s.IndexOf(".");
      

  12.   

    5.555
    decimal.Round() 是以四舍六入五成双!
    结果 5.55
    .ToString("N2") 是纯粹的四舍五入!
    结果5.56楼主祝你好运。
      

  13.   

            /**
     * 四舍五入
     * 
     * @param num
     *            要四舍五入的数字
     * @param roundBit
     *            四舍五入位数 正数表示:小数点后位数;负数表示:小数前位数
     * @return 四舍五入后的数字
     */
    public static double round(double num, int roundBit) {
    int piontBit = 1;
    double numtmp = 0;
    if (roundBit < 0) {
    String tmpstr = "1";
    roundBit = Math.abs(roundBit);
    for (int i = 0; i < roundBit; i++) {
    tmpstr += "0";
    }
    piontBit = Integer.parseInt(tmpstr);
    roundBit = 0;
    num = (double) (num / piontBit);
    }
    BigDecimal b = new BigDecimal(Double.toString(num));
    BigDecimal one = new BigDecimal("1");
    numtmp = b.divide(one, roundBit, BigDecimal.ROUND_HALF_UP)
    .doubleValue();
    return numtmp * piontBit; }  
      

  14.   


    int Round( float f )
    {
        return _mm_cvt_ss2si( _mm_set_ss(f+f+0.5f) >> 1 );
    }
    int Floor( float f )
    {
        return _mm_cvt_ss2si( _mm_set_ss(f+f-0.5f) >> 1 );
    }