[英]Using float type or double output a decimal number in Java(eclipse)
I wanted the output to be 0.123456789123456789
. 我希望输出为
0.123456789123456789
。 But, result is 0.123456789
in float type. 但是,结果是浮点型的
0.123456789
。 0.12345678912345678
in double type. 双重类型为
0.12345678912345678
。 So, I tried using %030.19f,e
but this doesn't work either. 因此,我尝试使用
%030.19f,e
但这也不起作用。 How do I output 0.123456789123456789
? 我如何输出
0.123456789123456789
?
For bigger numbers you can use BigDecimal. 对于更大的数字,您可以使用BigDecimal。 For example:
例如:
import java.math.BigDecimal;
public class HelloWorld{
public static void main(String []args){
BigDecimal bdcm=new BigDecimal("0.123456789123456789");
System.out.println(bdcm);
BigDecimal bdcm2=new BigDecimal("100.123456789123456789");
System.out.println(bdcm.add(bdcm2));
}
}
And the output is proper :) 和输出是正确的:)
Don't use float
or double
if you need to print exact values. 如果需要打印精确值,请不要使用
float
或double
。
Use instead a BigDecimal
that is a class to hold 改用
BigDecimal
作为类来保存
Immutable, arbitrary-precision signed decimal numbers
不可变, 任意精度的带符号十进制数字
The problem using float
and double
is that they suffer for the rounding related to binary decimal numbers. 使用
float
和double
的问题在于它们会遭受与二进制十进制数字有关的舍入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.