- public class Test
- {
- public static void main(String[] args)
- {
- double x = 0.01;
- double y = 0.09;
- System.out.println(x + y);
- }
- }
复制代码 输出结果是0.09999999999999999而不是0.1解决方法一:将x,y改为float
- public class Test
- {
- public static void main(String[] args)
- {
- /*double x = 0.01;
- double y = 0.09;*/
- float x = (float) 0.01;
- float y = (float) 0.09;
- System.out.println(x + y);
- }
- }
复制代码 输出结果为:0.1
如果把x,y分别改为float的0.01和0.04,在相加,
- public class Test
- {
- public static void main(String[] args)
- {
- /*double x = 0.01;
- double y = 0.09;*/
- float x = (float) 0.01;
- float y = (float) 0.04;
- System.out.println(x + y);
- }
- }
复制代码 结果居然是0.049999997
方法二:使用DecimalFormat
- import java.text.DecimalFormat;
- public class A
- {
- public static void main(String[] args)
- {
- float a = (float) 0.01;
- float b = (float) 0.04;
- DecimalFormat df = new DecimalFormat("#0.00");
- System.out.println(df.format(a+b));
- }
- }
复制代码 输出结果:0.05,此方法无论是double类型还是float类型都适用!
|
|