2010-12-12 149 views
5

我有一個DecimalFormat對象,當我顯示它們時,我正用它將所有的double值格式化爲一組數字(讓我們說2)。我希望它通常格式化爲2位小數,但我總是希望至少有一位有效數字。例如,如果我的值是0.2,那麼我的格式化程序吐出0.20,這很好。但是,如果我的值是0.000034,我的格式化程序將會吐出0.00,而我更喜歡我的格式化程序吐出0.00003。在Java/Android中將至少一個有效數字格式化爲雙倍至少一個有效數字

Objective-C中的數字格式化程序非常簡單,我可以設置我想在2處顯示的最大數字位數和在1處顯示最小有效位數,它會生成我想要的輸出,但怎麼能我在Java中執行它?

我很欣賞任何人都可以提供給我的幫助。

凱爾

編輯:我感興趣的是爲0.00004四捨五入的值,從而0.000037顯示器。

回答

2

它的效率不高,因此,如果您執行此操作通常我想嘗試另一種解決方案,但如果你只是偶爾把它這個方法會奏效。

import java.text.DecimalFormat; 
public class Rounder { 
    public static void main(String[] args) { 
     double value = 0.0000037d; 
     // size to the maximum number of digits you'd like to show 
     // used to avoid representing the number using scientific notation 
     // when converting to string 
     DecimalFormat maxDigitsFormatter = new DecimalFormat("#.###################"); 
     StringBuilder pattern = new StringBuilder().append("0.00"); 
     if(value < 0.01d){ 
      String s = maxDigitsFormatter.format(value); 
      int i = s.indexOf(".") + 3; 
      while(i < s.length()-1){ 
       pattern.append("0"); 
       i++; 
      } 
     } 
     DecimalFormat df = new DecimalFormat(pattern.toString()); 
     System.out.println("value   = " + value); 
     System.out.println("formatted value = " + maxDigitsFormatter.format(value)); 
     System.out.println("pattern   = " + pattern); 
     System.out.println("rounded   = " + df.format(value)); 
    } 
} 
+0

謝謝,網絡和尚,看起來就像我需要的東西! – 2010-12-16 04:05:31

+0

@凱爾,您的歡迎! – 2010-12-17 18:54:15

0
import java.math.BigDecimal; 
import java.math.MathContext; 


public class Test { 

    public static void main(String[] args) { 
     String input = 0.000034+""; 
     //String input = 0.20+""; 
     int max = 2; 
     int min =1; 
     System.out.println(getRes(input,max,min)); 
    } 

    private static String getRes(String input,int max,int min) { 
     double x = Double.parseDouble(((new BigDecimal(input)).unscaledValue().intValue()+"").substring(0,min)); 
     int n = (new BigDecimal(input)).scale(); 
     String res = new BigDecimal(x/Math.pow(10,n)).round(MathContext.DECIMAL64).setScale(n).toString(); 
     if(n<max){ 
      for(int i=0;i<max;i++){ 
       res+="0"; 
      } 
     } 
     return res; 
    } 
} 
+0

Hey Zawhtut!首先,謝謝你的回覆。不過,我還有其他一些問題。首先,我對四捨五入感興趣,而不是截斷,所以我想0.000037表示爲0.00004而不是0.00003。其次,如果我的原始數字是0.0000372,由於我輸入數字的最後一個有效數字與e-7位置相同,因此在我看來,您提供的算法將產生3e-7。我基於此?再次感謝您提供的任何額外說明! – 2010-12-14 18:52:29

+0

嘿凱爾。好像你已經有了答案。順便問一個好問題。 – zawhtut 2010-12-23 14:09:02

相關問題