6

我有一个 DecimalFormat 对象,当我显示它们时,我用它来将所有双精度值格式化为一组数字(比如说 2)。我希望它通常格式化为 2 位小数,但我总是想要至少一个有效数字。例如,如果我的值为 0.2,那么我的格式化程序会吐出 0.20,这很好。但是,如果我的值是 0.000034,我的格式化程序会吐出 0.00,我希望我的格式化程序吐出 0.00003。

Objective-C 中的数字格式化程序非常简单,我可以将我想显示的最大位数设置为 2,将有效位数的最小位数设置为 1,它会产生我想要的输出,但我该怎么做爪哇?

我感谢任何人可以为我提供的任何帮助。

凯尔

编辑:我有兴趣将值四舍五入,因此 0.000037 显示为 0.00004。

4

2 回答 2

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));
    }
}
于 2010-12-15T18:26:15.240 回答
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;
    }
}
于 2010-12-13T14:35:13.427 回答