如何在java中用科学记数法表示数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19984040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to express numbers in scientific notation in java?
提问by OrangeCalx01
I'm writing a program that deals with planets' mass and diameter; These quantities are expressed in scientific notation. My question is NOT, mind you, NOT how does one print large numbers the right way (That's using printf(), duh), its how I would... "type" these numbers, I guess you could say. For example, the mass of mercury is expressed:
我正在编写一个处理行星质量和直径的程序;这些量以科学记数法表示。我的问题不是,请注意,不是一个人如何以正确的方式打印大数字(那是使用 printf(),废话),我会如何......“输入”这些数字,我想你会说。例如,汞的质量表示为:
3.30 x 10?23
And in my array of planet masses, an element would look:
在我的行星质量数组中,一个元素看起来像:
33.0 * Math.pow(10, 23)
However, I don't quite think this is the right way - it looks like it would throw an exception... So how could I express large numbers like that from a programmer's perspective? Thanks!
但是,我不太认为这是正确的方法 - 看起来它会抛出异常......那么我怎么能从程序员的角度表达这样的大数字呢?谢谢!
采纳答案by rgettman
Section 3.10.2 of the JLStalks about floating-point literals in Java. In short, provide the decimal part as if it were scientific notation, but instead of x 10^23
you would write e23
:
JLS 的第 3.10.2 节讨论了 Java 中的浮点文字。简而言之,提供小数部分就好像它是科学记数法一样,但x 10^23
你会写e23
:
3.30e23
To write one with a negative exponent, you can do that easily also for 6.67 x 10^(-11)
:
用负指数写一个,你也可以很容易地做到6.67 x 10^(-11)
:
6.67e?11
回答by SLaks
Java does support scientific notation:
Java 确实支持科学记数法:
3.30e23
回答by rgettman
You can try initializing a long variable and try casting it as a double/float. That may work but I'm not a 100%
您可以尝试初始化一个 long 变量并尝试将其转换为 double/float。这可能有效,但我不是 100%