Java double 到具有特定精度的字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20353319/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java double to string with specific precision
提问by user3009344
I would like to convert double
into String
. I want it to have as few digits as possible and maximally 6.
我想转换double
成String
. 我希望它具有尽可能少的数字,最多为 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?
所以我发现String.format("%.6f", d)
哪个将 my 转换100.0
为100.000000
. 最大精度工作正常,但我希望将其转换为100
(最小精度)。你知道什么方法是这样工作的吗?
采纳答案by Thomas
Use DecimalFormat
: new DecimalFormat("#.0#####").format(d)
.
使用DecimalFormat
:new DecimalFormat("#.0#####").format(d)
。
This will produce numbers with 1 to 6 decimal digits.
这将产生具有 1 到 6 个十进制数字的数字。
Since DecimalFormat
will use the symbols of the default locale, you might want to provide which symbols to use:
由于DecimalFormat
将使用默认语言环境的符号,您可能需要提供要使用的符号:
//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 #.######
.
要将 100.0 格式化为 100,请使用格式字符串#.######
。
Note that DecimalFormat
will round by default, e.g. if you pass in 0.9999999
you'll get the output 1
. If you want to get 0.999999
instead, provide a different rounding mode:
请注意,DecimalFormat
默认情况下会舍入,例如,如果您传入,0.9999999
您将获得输出1
。如果你想得到0.999999
,请提供不同的舍入模式:
DecimalFormat formatter = new DecimalFormat("#.######", DecimalFormatSymbols.getInstance( Locale.ENGLISH ));
formatter.setRoundingMode( RoundingMode.DOWN );
String s = formatter.format(d);
回答by Paul Samsotha
String.format("%.0", d)
will give you no decimal places
String.format("%.0", d)
不会给你小数位
-or-
-或者-
String.format("%d", (int)Math.round(f))
String.format("%d", (int)Math.round(f))
回答by brettw
This is a cheap hack that works (and does not introduce any rounding issues):
这是一个有效的廉价黑客(并且不会引入任何舍入问题):
String string = String.format("%.6f", d).replaceAll("(\.\d+?)0*$", "");
回答by Travis
Couldn't you just make a setPrecision function, sort of like this
你能不能做一个 setPrecision 函数,有点像这样
private static String setPrecision(double amt, int precision){
return String.format("%." + precision + "f", amt);
}
then of course to call it
那么当然要调用它
setPrecision(variable, 2); //
Obviously you can tweek it up for rounding or whatever it is you need to do.
显然,您可以将其调整为四舍五入或您需要做的任何事情。