Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
829 views
in Technique[技术] by (71.8m points)

java - Use DecimalFormat to get varying amount of decimal places

So I want to use the Decimal Format class to round numbers:

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. However, I want to round value to an unknown amount of decimal places, indicated by a separate integer called numPlaces. Is there a way I could accomplish this by using the Decimal Formatter?

e.g. If numPlaces = 3 and value = 10.555, value needs to be rounded to 3 decimal places

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...