Use DecimalFormat to get a different number 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 valuewill be rounded to two decimal places, because there are two #s. However, I want to round valueto an unknown number of decimal places, denoted by a separate integer numPlaces. Is there a way I could do this using a decimal formatter?

eg. If numPlaces = 3and value = 10.555, valueit is necessary to round to three decimal places

+3
source share
4 answers

Create a method to create a specific number #for the string, for example:

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

DecimalFormat - , String.format PrintStream.format .

int precision = 4; // example
String formatString = "%." + precision + "f";
double value = 7.45834975; // example
System.out.format(formatString, value); // output = 7.4583
+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));
+1

DecimalFormat,, BigDecimal.round() MathContext , BigDecimal.toString().

-1

All Articles