Java 对于简单的浮点截断,使用DecimalFormat是否太多?

Java 对于简单的浮点截断,使用DecimalFormat是否太多?,java,decimalformat,Java,Decimalformat,我突然需要从浮点数中去掉多余的数字,所以我查看工具箱,发现DecimalFormat是可用的 虽然创建一个新对象只是为了从一个数字上切掉一些额外的数字似乎相当昂贵,所以我编写了一个小程序来测试它 public class Snippet { static float unformatted = -542.347543274623876F; static int fractionDigits = 2; public static void main(String[] a

我突然需要从浮点数中去掉多余的数字,所以我查看工具箱,发现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));
    }

}
不管我运行它多少次,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);
请在此处尝试:


它的作用是,将它乘以你想要的十进制数字的10倍,将它转换成一个整数,去掉剩余的数字,然后再除以十进制数字的10倍,将它转换回十进制。如果您使用float,它也应该适用于float。

您确定应该使用float而不是BigDecimal吗?请注意,一旦您执行了parseFloat,确实会有额外的小数位数,即使您并不总是看到它们。最接近-542.34的浮点是-542.3400268546875。您的基准测试是不相关的——即使在非JIT编译语言中,您也需要运行几千次迭代;在JIT编译语言中,事情更复杂。。。复杂的此外,创建DecimalFormat并不是免费的——只需在基准代码之外创建一次,您的声明本身就是有缺陷的-542.347543274623876F等于-542.34753,即使使用double也不够,因为-542.347543274623876d等于-542.34754327462388。如果这其中任何一个都要精确,你就需要更精确。示例:您只有两个选择:DecimalFormat或BigDecimal。您不会让我相信十进制格式是应用程序中决定速率的一个步骤。这当然是假设您的双精度或浮点值实际上可以保留小数点后两位的值-这很可能不是事实。@Boristespider,OP说它是一个浮点,如果它以浮点开始,然后,由于它以较低的精度结束,因此它将以浮点数结束拟合。我用双精度表示,因为OP的第一个赋值语句导致精度损失很大。@Boristeider,问题不要求任意精度,为什么要使用字符串?
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);