繁体   English   中英

对于简单的浮点截断使用DecimalFormat太多了吗?

[英]Is using DecimalFormat too much for simple float truncation?

我突然需要将浮点数中多余的数字切掉,因此我在工具箱中查看了一下,发现DecimalFormat可用。

尽管创建一个新对象只是为了将数字中的多余数字砍掉似乎很昂贵,所以我提出了一个小程序对其进行测试。

public class Snippet {

    static float unformatted = -542.347543274623876F;
    static int fractionDigits = 2;

    public static void main(String[] args){

        long a = System.nanoTime();
        System.out.println(stringMethod(unformatted));
        long b = System.nanoTime();
        System.out.println(formatMethod(unformatted));
        long c = System.nanoTime();
        System.out.println(stringMethod2(unformatted));
        long d = System.nanoTime();

        System.out.println("OP1:"+(b-a));
        System.out.println("OP2:"+(c-b));
        System.out.println("OP3:"+(d-c));

    }

    private static float stringMethod(float number){
        String unfStr = String.valueOf(number);
        for(int i=0;i<unfStr.length();i++){
            if(unfStr.charAt(i) == '.'){
                return Float.parseFloat(unfStr.substring(0, i+1+fractionDigits));
            }
        }
        return Float.parseFloat(unfStr);
    }

    private static float stringMethod2(float number){
        String unfStr = String.format("%."+(fractionDigits+1)+"f",number);
        return Float.parseFloat(unfStr.substring(0,unfStr.length()-1));
    }

    private static float formatMethod(float number){
        DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(fractionDigits);
        df.setRoundingMode(RoundingMode.DOWN);
        return Float.parseFloat(df.format(unformatted));
    }

}

OUTPUT:

-542.34
-542.34
-542.34
OP1:1937181
OP2:32609426
OP3:3111908

无论我运行多少次, DecimalFormat方法都无法跟上。

所以我想这里的问题是,除了代码可读性之外,是否有任何理由使用DecimalFormat而不是为简单的浮点截断创建自己的方法?

这是一种数值方法:

double d = -542.347543274623876;
System.out.println(d);
int n = 2; // decimal digits

double p = Math.pow(10,n);
d = Math.floor((int)(p*d))/p;
System.out.println(d);

在这里尝试: http : //ideone.com/wIhBpL

它的作用是将其乘以所需小数位数的10倍,将其转换为整数(将剩余的位数除掉),然后通过除以小数位数的10倍,将其转换回十进制。 如果您改用float ,它也应该适用于float

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM