簡體   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