[英]Parsing a floating point number with mantissa in Java
Using the standard Java Double
class to parse a floating point number with mantissa seems to omit the + sign from the exponent. 使用标准的Java
Double
类解析尾数浮点数似乎忽略了指数中的+号。
For example: 例如:
Double.parseDouble("1258124354E-28") returns 1.258124354E-19, but
Double.parseDouble("1243544322E+24") returns 1.243544322E33 (not E+33)
Is there any way to get the + sign using Double, without string post-processing? 有没有办法使用Double获得+符号,而无需进行字符串后处理?
The BigDecimal
class does a better job, eg BigDecimal
类做得更好,例如
new BigDecimal("1243544322E+24").toString() does return 1.243544322E+33
but it is generally slower than Double
, which shows in intensive processing. 但通常比
Double
慢,而Double
在密集处理中显示。
You need to differentiate between the value stored in a double
and its string representation. 您需要区分存储在
double
的值及其字符串表示形式。
A double
doesn't store a textual representation at all. double
根本不存储文本表示形式。 1.243544322E33 is 1.243544322E+33. 1.243544322E33 是 1.243544322E + 33。 They're the same value.
它们具有相同的价值。
Now if you want to work on how you format a double
value back to a String
, that's a different matter - but the parsing you're doing is fine. 现在,如果您想研究如何将
double
值格式化为String
,那是另一回事了-但是您正在执行的解析就可以了。 You're not losing any information. 您不会丢失任何信息。
Jon is correct as above, its representing it correctly in memory. Jon如上所述是正确的,它在内存中正确地表示了它。 If you want it to display with the + on the mantissa then you are talking about string formatting the double.
如果您希望它在尾数上显示为+,那么您在说的是字符串格式的双精度格式。
Long winded official formatter reference 冗长的官方格式化程序参考
import java.util.Formatter;
double myDouble = Double.parseDouble("1243544322E+24");
Formatter formatter = new Formatter();
formatter.format("%+E", myDouble); //This should return with what you want, though with an extra + infront of the number
I haven't ran this code so I'm not 100% sure it will do the job. 我尚未运行此代码,因此我不是100%确信它将完成这项工作。 The + in the format specifier forces it to place a + or - sign for any number... I believe that extends to the mantissa.
格式说明符中的+强制它为任何数字放置+或-符号...我认为这会扩展到尾数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.