public class ErrorTest
{
public static void main(String[] args)
{
double a1=0.0184d;
double b1=a1*100;
double a2=0.0282d;
double b2=a2*100;
float a3=0.0184f;
float b3=a3*100;
System.out.println(b1);//1.8399999999999999
System.out.println(b2);//2.82
System.out.println(b3);//1.84
}
}
//b1为什么不是1.84? 谁能解释一下上面的问题...
{
public static void main(String[] args)
{
double a1=0.0184d;
double b1=a1*100;
double a2=0.0282d;
double b2=a2*100;
float a3=0.0184f;
float b3=a3*100;
System.out.println(b1);//1.8399999999999999
System.out.println(b2);//2.82
System.out.println(b3);//1.84
}
}
//b1为什么不是1.84? 谁能解释一下上面的问题...
a = new BigDecimal("20.1"); // 第二,数字千万不要用浮点数初始化,要用字符串
b = new BigDecimal("10");
System.out.println("a=" + a + "; b =" + b + "; a*b = " + a.multiply(b));
a = new BigDecimal("20.01");
b = new BigDecimal("10");
System.out.println("a = " + a + "; b =" + b + "; a*b = " + a.multiply(b));
对超过double值范围的或者说:高精度(或任意精度)的表达式求值问题,请楼主使用著名的JEP包吧(JAVA表达式求值包,功能很强大!)
如:楼主的例子(引申一下,变得更复杂些):
234535098234095890234589038.9999999998888888888888888888888888888888*(923948723894723947230598.7777777777777777+12.00999999999999999999999999999999999999999999999999)
值为:
2.166984047219166216979260416663208E+50(精度我设定的是:MathContext.DECIMAL128) 使用的参考代码:(总共三步)
Jep jep = new Jep(new BigDecComponents(MathContext.DECIMAL128));//生成指定计算精度的jep对象
Object rs=jep.evaluate(
jep.parse("234535098234095890234589038.9999999998888888888888888888888888888888*(923948723894723947230598.7777777777777777+12.00999999999999999999999999999999999999999999999999)"
));//对指定的任意表达式进行求值
System.out.println(rs);//打印表达式的值