在 Java 中添加两个浮点值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13523207/
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
Add two float values in Java
提问by user1845286
Acually i tried to add two float values in Java like this:
Acumally 我尝试在 Java 中添加两个浮点值,如下所示:
import java.text.DecimalFormat;
class ExactDecimalValue
{
final strictfp static public void main(String... arg)
{
float f1=123.00000f;
float f2=124.00000f;
float f3=f1+f2;
System.out.println(f1+f2);
System.out.println("sum of two floats:"+f3);
/*my expected output is:247.00000
but comming output is:247.0 and 247*/
}
}
Now what i can do to get the value in this format:247.00000.
现在我可以做些什么来获得这种格式的值:247.00000。
回答by bigfetz
This will work:
这将起作用:
float f1=123.00000f;
float f2=124.00000f;
float f3=f1+f2;
System.out.println(f1+f2);
System.out.printf("%.5f", f3);
Whenever I want to format floats I always use printf.
每当我想格式化浮点数时,我总是使用 printf。
回答by H31IX
It's not that the actual addition is wrong, it's just that printing the value out is assuming that you don't need the exact value, in layman's terms... For more information about floating point precision, see: Round-Off Error.
并不是实际的加法是错误的,只是打印出来的值假设您不需要确切的值,用外行的话来说......有关浮点精度的更多信息,请参阅:舍入误差。
See this answer on specifying decimal output of a float: How to display an output of float data with 2 decimal places in Java?
请参阅有关指定浮点数的十进制输出的答案:如何在 Java 中显示带有 2 个小数位的浮点数据的输出?
回答by Amit Gupta
You can use DecimalFormat class for setting up the precision
您可以使用 DecimalFormat 类来设置精度
float f1=123.00000f;
float f2=124.00000f;
float f3=f1+f2;
DecimalFormat f = new DecimalFormat("0.00000");
System.out.println(f.format(f3));
the output will be 247.00000
输出将是 247.00000
回答by Shyam
Method 1:
方法一:
Float f3 = Float.sum(f1, f2);
Method 2:
方法二:
Float f3 = f1.floatValue()+f2.floatValue();