任何人都可以解释以下示例中的 double 和 float 数据类型的行为。为什么精度值会发生变化?
public class TestClass{
public static void main(String[] args) {
String st = "4.45";
double i = Double.parseDouble(st);
float fff = Float.parseFloat(st);
System.out.println("Float 4.45 outputs : *******************************");
System.out.println(fff);
int fpp = (int) (fff *100);
System.out.println(fff *100);
System.out.println(fpp);
System.out.println("Double 4.45 outputs : *******************************");
System.out.println(i);
int p = (int) (i *100);
System.out.println(i *100);
System.out.println(p);
String str = "9.45";
double ii = Double.parseDouble(str);
float ff = Float.parseFloat(str);
System.out.println("Float 9.45 outputs : *******************************");
System.out.println(ff);
int fp = (int) (ff *100);
System.out.println(ff *100);
System.out.println(fp);
System.out.println("Double 9.45 outputs : *******************************");
System.out.println(ii);
int pp = (int) (ii *100);
System.out.println(ii *100);
System.out.println(pp);
String strr = "9.40";
double iir = Double.parseDouble(strr);
float ffr = Float.parseFloat(strr);
System.out.println("Float 9.40 outputs : *******************************");
System.out.println(ffr);
int fpr = (int) (ffr *100);
System.out.println(ffr *100);
System.out.println(fpr);
System.out.println("Double 9.40 outputs : *******************************");
System.out.println(iir);
int ppr = (int) (iir *100);
System.out.println(iir *100);
System.out.println(ppr);
}
}
输出:
浮点 4.45 输出:********************************
4.45
444.99997
444
双 4.45 输出:********************************
4.45
445.0
445
浮点 9.45 输出:********************************
9.45
945.0
945
双 9.45 输出:********************************
9.45
944.9999999999999
944
浮点 9.40 输出:********************************
9.4
939.99994
939
双 9.40 输出:********************************
9.4
940.0
940
最佳答案
对Float
、Double
及其原始对应项执行运算很容易丢失小数精度(例如ii * 100
您打印的值)。
这就是为什么您通常使用 java.math
包中的类来进行货币相关计算(例如 BigDecimal
)。
关于java - double 和 float 据类型的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34720099/