使用 String.format 的 Java 十进制格式?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/433958/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:32:51  来源:igfitidea点击:

Java decimal formatting using String.format?

javaformattingdecimal

提问by richs

I need to format a decimal value into a string where I always display at lease 2 decimals and at most 4.

我需要将十进制值格式化为一个字符串,其中我总是显示至少 2 位小数,最多 4 位小数。

So for example

所以例如

"34.49596" would be "34.4959" 
"49.3" would be "49.30"

Can this be done using the String.format command?
Or is there an easier/better way to do this in Java.

这可以使用 String.format 命令完成吗?
或者在 Java 中是否有更简单/更好的方法来做到这一点。

采纳答案by Richard Campbell

You want java.text.DecimalFormat.

你想要 java.text.DecimalFormat。

DecimalFormat df = new DecimalFormat("0.00##");
String result = df.format(34.4959);

回答by duffymo

You want java.text.DecimalFormat

你想要 java.text.DecimalFormat

回答by cagcowboy

java.text.NumberFormat is probably what you want.

java.text.NumberFormat 可能就是你想要的。

回答by Yuval Adam

Here is a small code snippet that does the job:

这是一个完成这项工作的小代码片段:

double a = 34.51234;

NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(4);
df.setRoundingMode(RoundingMode.DOWN);

System.out.println(df.format(a));

回答by Brian Clapper

NumberFormat and DecimalFormat are definitely what you want. Also, note the NumberFormat.setRoundingMode()method. You can use it to control how rounding or truncation is applied during formatting.

NumberFormat 和 DecimalFormat 绝对是你想要的。另外,注意NumberFormat.setRoundingMode()方法。您可以使用它来控制在格式化期间如何应用舍入或截断。

回答by mostar

Yes you can do it with String.format:

是的,你可以这样做String.format

String result = String.format("%.2f", 10.0 / 3.0);
// result:  "3.33"

result = String.format("%.3f", 2.5);
// result:  "2.500"