问题
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
回答1:
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));
回答2:
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.
int precision = 4; // example
String formatString = "%." + precision + "f";
double value = 7.45834975; // example
System.out.format(formatString, value); // output = 7.4583
回答3:
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));
回答4:
I was looking for a method that would return like
300.0 to 300
525.25000 to 525.25
75.12345000 to 75.12345
So made a function to do the same
public static String RoundedDouble(double val) {
String s = String.valueOf(val);
if (s.contains("."))
while (!s.equals(""))
if (s.contains(".") && (s.endsWith("0") || s.endsWith(".")))
s = s.substring(0, s.length() - 1);
else break;
return s;
}
回答5:
If you're not absolutely bound to use DecimalFormat,
you could use BigDecimal.round()
for this in conjunction with MathContext
of the precision that you want, then just BigDecimal.toString().
来源:https://stackoverflow.com/questions/21667864/use-decimalformat-to-get-varying-amount-of-decimal-places