所以我想使用 Decimal Format 类来四舍五入:
double value = 10.555;
DecimalFormat fmt = new DecimalFormat ("0.##");
System.out.println(fmt.format(value));
在这里,变量 value
将四舍五入到小数点后两位,因为有两个 #
。但是,我想将 value
舍入到未知数量的小数位数,由一个名为 numPlaces
的单独整数表示。有没有一种方法可以通过使用 Decimal Formatter 来实现?
例如如果numPlaces = 3
和value = 10.555
,value
需要四舍五入到小数点后3位
最佳答案
创建一个方法来生成一定数量的#
到一个字符串,像这样:
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));
关于java - 使用 DecimalFormat 获取不同数量的小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21667864/