我想将 double
转化为 String
。希望尽可能少的数字且最多6个。
所以我找到了 String.format("%.6f", d)
可以将我的 100.0
转换成 100.000000
。
最大精度是正确的,但我希望将其转换为 100
(最小精度)。
您有任何想法吗?
我想将 double
转化为 String
。希望尽可能少的数字且最多6个。
所以我找到了 String.format("%.6f", d)
可以将我的 100.0
转换成 100.000000
。
最大精度是正确的,但我希望将其转换为 100
(最小精度)。
您有任何想法吗?
使用 DecimalFormat
: new DecimalFormat("#.0#####").format(d)
。
这将生成1到6位小数的数字。
由于DecimalFormat
将使用默认语言环境的符号,您可能需要提供要使用的符号:
//Format using english symbols, e.g. 100.0 instead of 100,0
new DecimalFormat("#.0#####", DecimalFormatSymbols.getInstance( Locale.ENGLISH )).format(d)
为将100.0格式化为100,请使用格式字符串#.######
。DecimalFormat
会进行四舍五入,例如,如果您输入0.9999999
,则会输出1
。如果您想获得0.999999
,请提供不同的舍入模式:DecimalFormat formatter = new DecimalFormat("#.######", DecimalFormatSymbols.getInstance( Locale.ENGLISH ));
formatter.setRoundingMode( RoundingMode.DOWN );
String s = formatter.format(d);
这是一个简单而有效的技巧(不会引入任何舍入问题):
String string = String.format("%.6f", d).replaceAll("(\\.\\d+?)0*$", "$1");
String.format("%.0f", d)
将不会保留小数位。
-或-
String.format("%d", (int)Math.round(f))
你能不能创建一个类似这样的setPrecision
函数呢?
private static String setPrecision(double amt, int precision){
return String.format("%." + precision + "f", amt);
}
setPrecision(variable, 2); //