使用DecimalFormat获取不同数量的小数位

时间:2014-02-10 01:58:33

标签: java string decimalformat

所以我想使用Decimal Format类来舍入数字:

double value = 10.555;

DecimalFormat fmt = new DecimalFormat ("0.##");

System.out.println(fmt.format(value));

这里,变量value将四舍五入到小数点后两位,因为有两个# s。但是,我想将value舍入到未知的小数位数,由一个名为numPlaces的单独整数表示。有没有办法通过使用十进制格式化器来实现这个目的?

e.g。如果numPlaces = 3value = 10.555value需要四舍五入到小数点后3位

4 个答案:

答案 0 :(得分:6)

创建一个方法,为字符串生成一定数量的#,如下所示:

public static String generateNumberSigns(int n) {

    String s = "";
    for (int i = 0; i < n; i++) {
        s += "#";
    }
    return s;
}

然后使用该方法生成一个字符串以传递给DecimalFormat类:

double value = 1234.567890;
int numPlaces = 5;

String numberSigns = generateNumberSigns(numPlaces);
DecimalFormat fmt = new DecimalFormat ("0." + numberSigns);

System.out.println(fmt.format(value));

或者只是在没有方法的情况下完成所有操作:

double value = 1234.567890;
int numPlaces = 5;

String numberSigns = "";
for (int i = 0; i < numPlaces; i++) {
    numberSigns += "#";
}

DecimalFormat fmt = new DecimalFormat ("0." + numberSigns);

System.out.println(fmt.format(value));

答案 1 :(得分:2)

这个怎么样?

double value = 10.5555123412341;
int numPlaces = 5;
String format = "0.";

for (int i = 0; i < numPlaces; i++){
    format+="#";
}
DecimalFormat fmt = new DecimalFormat(format);

System.out.println(fmt.format(value));

答案 2 :(得分:2)

如果您不需要将DecimalFormat用于任何其他目的,更简单的解决方案是使用String.formatPrintStream.format并以与Mike Yaworski解决方案类似的方式生成格式字符串。

int precision = 4; // example
String formatString = "%." + precision + "f";
double value = 7.45834975; // example
System.out.format(formatString, value); // output = 7.4583

答案 3 :(得分:-2)

如果您不是绝对必须使用DecimalFormat,,那么您可以将BigDecimal.round()MathContext精度结合使用,然后只需BigDecimal.toString(). < / p>