Java双精确到字符串 [英] Java double to string with specific precision
问题描述
所以我发现String.format(%。6f,d)将我的100.0转换为100.000000。
最大精度工作正常,但我希望将其转换为100(最小精度)。
你有什么想法吗?
使用 DecimalFormat
: new DecimalFormat(#。0 #####)。format(d)
。
这将产生1到6位十进制数字。
由于 DecimalFormat
将使用符号的默认语言环境,您可能需要提供要使用的符号:
//使用英文符号格式,例如100.0而不是100,0
/ pre>
new DecimalFormat(#。0 #####,DecimalFormatSymbols.getInstance(Locale.ENGLISH))。format(d)
为了格式化为100.0到100,请使用格式字符串
#。######
请注意,缺省情况下,
DecimalFormat
将轮回,例如如果您通过0.9999999,您将得到1
的输出。如果您想要获得0.999999
,请提供不同的舍入模式:formatter.setRoundingMode(RoundingMode.DOWN);
String s = formatter.format(d);
I would like to convert double into string. I want it to have as few digits as possible and maximally 6 So i found String.format("%.6f", d) which converts my 100.0 into 100.000000. Max precision works correctly, but i would like it to be converted to 100(minimum precision). Have you got any idea what method is working like that?
解决方案Use
DecimalFormat
:new DecimalFormat("#.0#####").format(d)
.This will produce numbers with 1 to 6 decimal digits.
Since
DecimalFormat
will use the symbols of the default locale, you might want to provide which symbols to use://Format using english symbols, e.g. 100.0 instead of 100,0 new DecimalFormat("#.0#####", DecimalFormatSymbols.getInstance( Locale.ENGLISH )).format(d)
In order to format 100.0 to 100, use the format string
#.######
.Note that
DecimalFormat
will round by default, e.g. if you pass in 0.9999999 you'll get the output1
. If you want to get0.999999
instead, provide a different rounding mode:DecimalFormat formatter = new DecimalFormat("#.######", DecimalFormatSymbols.getInstance( Locale.ENGLISH )); formatter.setRoundingMode( RoundingMode.DOWN ); String s = formatter.format(d);
这篇关于Java双精确到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!