java 格式化浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4733089/
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
Formatting Floating Point Numbers
提问by st0le
I have a variable of type double
, I need to print it in upto 3 decimals of precision but it shouldn't have any trailing zeros...
我有一个 type 变量double
,我需要以最多 3 位小数的精度打印它,但它不应该有任何尾随零...
eg. I need
例如。我需要
2.5 // not 2.500
2 // not 2.000
1.375 // exactly till 3 decimals
2.12 // not 2.120
I tried using DecimalFormatter
, Am i doing it wrong?
我尝试使用DecimalFormatter
,我做错了吗?
DecimalFormat myFormatter = new DecimalFormat("0.000");
myFormatter.setDecimalSeparatorAlwaysShown(false);
Thanks. :)
谢谢。:)
回答by Bart Kiers
Try the pattern "0.###"
instead of "0.000"
:
尝试模式"0.###"
而不是"0.000"
:
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) {
DecimalFormat df = new DecimalFormat("0.###");
double[] tests = {2.50, 2.0, 1.3751212, 2.1200};
for(double d : tests) {
System.out.println(df.format(d));
}
}
}
output:
输出:
2.5
2
1.375
2.12
回答by Marcin Pieciukiewicz
Your solution is almost correct, but you should replace zeros '0' in decimal format pattern by hashes "#".
您的解决方案几乎是正确的,但您应该用散列“#”替换十进制格式模式中的零“0”。
So it should look like this:
所以它应该是这样的:
DecimalFormat myFormatter = new DecimalFormat("#.###");
And that line is not necesary (as decimalSeparatorAlwaysShown
is false
by default):
而该行不necesary(如decimalSeparatorAlwaysShown
为false
默认):
myFormatter.setDecimalSeparatorAlwaysShown(false);
Here is short summary from javadocs:
以下是来自 javadocs 的简短摘要:
Symbol Location Localized? Meaning
0 Number Yes Digit
# Number Yes Digit, zero shows as absent
And the link to javadoc: DecimalFormat
以及指向 javadoc 的链接:DecimalFormat
回答by Rogach
Use NumberFormat class.
使用 NumberFormat 类。
Example:
例子:
double d = 2.5; NumberFormat n = NumberFormat.getInstance(); n.setMaximumFractionDigits(3); System.out.println(n.format(d));
double d = 2.5; NumberFormat n = NumberFormat.getInstance(); n.setMaximumFractionDigits(3); System.out.println(n.format(d));
Output will be 2.5, not 2.500.
输出将是 2.5,而不是 2.500。