我有double
我想转换为 String
的值具有以下格式限制的值:
number_of_fraction_digits = max( 0, 5 - number_of_integer_digits )
本质上,我希望尽可能将位数保留为 5,必要时四舍五入小数位。例如:
float String ------------------------- 1 1 100 100 100000 100000 99999 99999 99999.99 99999 9999.99 9999.9 999.99 999.99 23.34324 23.343
我研究过使用 DecimalFormat但据我所知,它并没有完全实现我所追求的目标。
它允许使用 setMaximumFractionDigits()
设置最大小数位数但据我所知,我必须计算整数位数并自己执行上述计算。
所以基本的问题是是否有一种漂亮、干净的内置方式以这种方式格式化数字。
最佳答案
public class SignificantFormat {
public static String formatSignificant(double value, int significant)
{
MathContext mathContext = new MathContext(significant, RoundingMode.DOWN);
BigDecimal bigDecimal = new BigDecimal(value, mathContext);
return bigDecimal.toPlainString();
}
public static void main(String[] args) {
double[] data = { 1, 100, 100000, 99999, 99999.99, 9999.99, 999.99, 23.34324 };
for(double d: data){
System.out.printf("Input: %10s \tOutput: %10s\n", Double.toString(d), formatSignificant(d, 5));
}
}
}
关于java - 使用最多五位数字来格式化 double 值,必要时四舍五入小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9978205/