如何在Java中打印2位小数的浮点数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2538787/
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
How to print a float with 2 decimal places in Java?
提问by via_point
Can I do it with System.out.print
?
我可以用System.out.print
吗?
采纳答案by Anthony Forloney
You can use the printf
method, like so:
您可以使用该printf
方法,如下所示:
System.out.printf("%.2f", val);
In short, the %.2f
syntax tells Java to return your variable (val
) with 2 decimal places (.2
) in decimal representation of a floating-point number (f
) from the start of the format specifier (%
).
简而言之,%.2f
语法告诉 Java从格式说明符 ( )的开头以浮点数val
( .2
) 的十进制表示形式返回带有 2 个小数位 ( ) 的变量f
( %
)。
There are other conversion characters you can use besides f
:
除了 ,您还可以使用其他转换字符f
:
d
: decimal integero
: octal integere
: floating-point in scientific notation
d
: 十进制整数o
: 八进制整数e
: 科学记数法中的浮点数
回答by Bozho
You can use DecimalFormat
. One way to use it:
您可以使用DecimalFormat
. 一种使用方法:
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
System.out.println(df.format(decimalNumber));
Another one is to construct it using the #.##
format.
另一种是使用#.##
格式构造它。
I find all formatting options less readable than calling the formatting methods, but that's a matter of preference.
我发现所有格式化选项都比调用格式化方法可读性差,但这是一个偏好问题。
回答by Kevin Sylvestre
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
回答by Uri
Look at DecimalFormat
Here is an example from the tutorial:
这是教程中的一个示例:
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
If you choose a pattern like "###.##", you will get two decimal places, and I think that the values are rounded up. You will want to look at the link to get the exact format you want (e.g., whether you want trailing zeros)
如果你选择像“###.##”这样的模式,你会得到两个小数位,我认为这些值是四舍五入的。您将需要查看链接以获得所需的确切格式(例如,是否需要尾随零)
回答by u7867
Many people have mentioned DecimalFormat
. But you can also use printf
if you have a recent version of Java:
很多人都提到过DecimalFormat
。但是,printf
如果您有最新版本的 Java,也可以使用:
System.out.printf("%1.2f", 3.14159D);
See the docs on the Formatter for more information about the printf format string.
回答by John P.
I would suggest using String.format()if you need the value as a String
in your code.
如果您需要在代码中将该值作为 a ,我建议使用String.format()String
。
For example, you can use String.format()
in the following way:
例如,您可以通过String.format()
以下方式使用:
float myFloat = 2.001f;
String formattedString = String.format("%.02f", myFloat);
回答by John P.
OK - str to float.
OK - str 浮动。
package test;
import java.text.DecimalFormat;
public class TestPtz {
public static void main(String[] args) {
String preset0 = "0.09,0.20,0.09,0.07";
String[] thisto = preset0.split(",");
float a = (Float.valueOf(thisto[0])).floatValue();
System.out.println("[Original]: " + a);
a = (float) (a + 0.01);
// Part 1 - for display / debug
System.out.printf("[Local]: %.2f \n", a);
// Part 2 - when value requires to be send as it is
DecimalFormat df = new DecimalFormat();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(2);
System.out.println("[Remote]: " + df.format(a));
}
}
Output:
输出:
run:
[Original]: 0.09
[Local]: 0.10
[Remote]: 0.10
BUILD SUCCESSFUL (total time: 0 seconds)
回答by Birk
A simple trick is to generate a shorter version of your variable by multiplying it with e.g. 100
, rounding it and dividing it by 100.0
again. This way you generate a variable, with 2 decimal places:
一个简单的技巧是通过将它与 eg 相乘100
、四舍五入并100.0
再次除以生成变量的较短版本。这样您就可以生成一个变量,带有2 个小数位:
double new_variable = Math.round(old_variable*100) / 100.0;
This "cheap trick" was always good enough for me, and works in any language (I am not a Java person, just learning it).
这个“便宜的技巧”对我来说总是足够好,并且适用于任何语言(我不是 Java 人,只是在学习它)。
回答by Aldin Philo
float floatValue=22.34555f;
System.out.print(String.format("%.2f", floatValue));
Output is 22.35. If you need 3 decimal points change it to "%.3f".
输出为 22.35。如果您需要 3 个小数点,请将其更改为“%.3f”。
回答by Pavan vadrevu
small simple program for demonstration:
用于演示的小简单程序:
import java.io.*;
import java.util.Scanner;
public class twovalues {
public static void main(String args[]) {
float a,b;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Values For Calculation");
a=sc.nextFloat();
b=sc.nextFloat();
float c=a/b;
System.out.printf("%.2f",c);
}
}