简体   繁体   English

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

[英]Use DecimalFormat to get varying amount of decimal places

So I want to use the Decimal Format class to round numbers:所以我想使用 Decimal Format 类来舍入数字:

double value = 10.555;

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

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

Here, the variable value would be rounded to 2 decimal places, because there are two # s.在这里,变量value将四舍五入到小数点后两位,因为有两个# However, I want to round value to an unknown amount of decimal places, indicated by a separate integer called numPlaces .但是,我想将value四舍五入到未知数量的小数位,由一个名为numPlaces的单独整数numPlaces Is there a way I could accomplish this by using the Decimal Formatter?有没有办法通过使用十进制格式器来实现这一点?

eg If numPlaces = 3 and value = 10.555 , value needs to be rounded to 3 decimal places例如,如果numPlaces = 3value = 10.555 ,则value需要四舍五入到小数点后 3 位

Create a method to generate a certain number of # to a string, like so:创建一个方法来为字符串生成一定数量的# ,如下所示:

public static String generateNumberSigns(int n) {

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

And then use that method to generate a string to pass to the DecimalFormat class:然后使用该方法生成一个字符串以传递给DecimalFormat类:

double value = 1234.567890;
int numPlaces = 5;

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

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

OR simply do it all at once without a method:或者只是在没有方法的情况下一次性完成:

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));

If you don't need the DecimalFormat for any other purpose, a simpler solution is to use String.format or PrintStream.format and generate the format string in a similar manner to Mike Yaworski's solution.如果您不需要 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

How about this?这个怎么样?

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));

如果您不是绝对必须使用DecimalFormat,您可以将BigDecimal.round()与所需精度的MathContext结合使用,然后只使用BigDecimal.toString().

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM