2010-12-12 144 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

相关问题