简体   繁体   English

字符串进行浮点/双解析

[英]String to float/double Parsing

When I try to parse the following string into a float and into a double : 当我尝试将以下字符串解析为float和double时:

String abc = "8.40";
System.out.println("Double Value: " + Double.parseDouble(abc) * 100);
System.out.println("Float Value: " + Float.parseFloat(abc) * 100);

I get two different results. 我得到两个不同的结果。

 Double Value: 840.0 Float Value: 839.99994 

But when I try the same code with multiplying the float and double by 10 or 1000 I get the similar results for both of them. 但是,当我尝试用相同的代码乘以float和double乘以10或1000时,对于两者而言,结果相似。

String abc = "8.40";
System.out.println("Double Value: " + Double.parseDouble(abc) * 10);
System.out.println("Float Value: " + Float.parseFloat(abc) * 10);

I get two similar results. 我得到两个类似的结果。

 Double Value: 84.0 Float Value: 84.0 

And when I try this : 当我尝试这个:

String abc = "8.40";
System.out.println("Double Value: " + Double.parseDouble(abc) * 1000);
System.out.println("Float Value: " + Float.parseFloat(abc) * 1000);

I get two similar results. 我得到两个类似的结果。

 Double Value: 8400.0 Float Value: 8400.0 

This will work fine: 这将正常工作:

System.out.println("Float Value: "+Math.round((float)Float.parseFloat(abc)*100));

So, this happens because of different representation of double and float , or more precise, about IEEE-754 rounding for float . 因此,发生这种情况是因为doublefloat表示形式不同,或更确切地说,是关于float IEEE-754舍入。 Read about it here . 在这里阅读。

float has a smaller range and precision, so double would be better when you have memory (which you do today). float具有较小的范围和精度,因此当您有内存(今天要这样做)时, double会更好。 But, they are both evil ! 但是,它们都是邪恶的 There is a better option in Java called BigDecimal and you should use it, since it doesn't have problem with size and today we have strong computers so we will not have problems with memory and speed when dealing with a large number of decimal numbers needing max precision. Java中有一个更好的选项,称为BigDecimal ,您应该使用它,因为它没有大小问题,并且今天我们拥有强大的计算机,因此在处理需要处理的大量十进制数时,我们不会遇到内存和速度问题最大精度。 For example, if you work on software that deals with a lot of money transactions, its a must to use BigDecimal . 例如,如果您使用的是处理大量资金交易的软件,则必须使用BigDecimal

It is true that double has more precision than float , but both of them suffer from the same problem: their value may not be exact, and they both have some (small) rounding error in their Least Significant Bit (LSB). 的确, double精度比float精度更高,但它们都遇到相同的问题:它们的值可能不准确,并且它们的最低有效位(LSB)都有一些(较小的)舍入误差。 This is clear in the first result you got: float value is not accurate. 这在您得到的第一个结果中很明显: float值不正确。 But when you multiply by 10 or 1000, the LSB is discarded from the result, and so you get the right answer for both float and double . 但是,当您乘以10或1000时,结果中的LSB将被丢弃,因此对于floatdouble ,您都将获得正确的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM