[英]How can i get sum in java?
I want to summation in java. 我想用java总结。
So, 所以,
For example,
例如,
1.123 + 1.123E-4 = 0.0123411234
1.123 + 1.123E-4 = 0.0123411234
So, How can i processing "E" in java? 那么,如何在Java中处理“ E”呢?
Use BigDecimal
: 使用
BigDecimal
:
public static void main( String[] args ) {
BigDecimal bigDecimal1 = new BigDecimal( "1.123" );
BigDecimal bigDecimal2 = new BigDecimal( "1.123E-4" );
BigDecimal sum = bigDecimal1.add( bigDecimal2 );
System.out.println( sum );
}
Output: 输出:
1.1231123
Use the BigDecimal
class. 使用
BigDecimal
类。 See http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String ) for a constructor that will take a string like "1.123E-4". 见http://docs.oracle.com/javase/1.5.0/docs/api/java/math/BigDecimal.html#BigDecimal(java.lang.String )的构造函数,将一个字符串,如“1.123E- 4“。
You mean something like this? 你的意思是这样的吗?
String a = "1.123";
String b = "1.123E-4";
double d1 = Double.valueOf(a);
double d2 = Double.valueOf(b);
System.out.println("sum = " + (d1 + d2));
Double's valueOf()
method can parse te E notation for you. Double的
valueOf()
方法可以为您解析E表示法。
And actually, the result is: 1.1231123 实际上,结果是:1.1231123
Well, did you even try it? 好吧,你甚至尝试过吗?
final class SciNotationTest {
public static void main(final String[] argv) {
final double sum = 1.123 + 1.123E-4;
System.out.println(sum);
assert 1.1231123 == sum;
}
}
C:\dev\scrap>javac SciNotationTest.java
C:\dev\scrap>java -ea SciNotationTest
1.1231123
You should be careful when using double
and testing equality without tolerance, as floating-point can often be imprecise. 使用
double
并在没有公差的情况下测试相等性时应小心,因为浮点数经常不精确。 If high-precision is what you're striving for, indeed use BigDecimal
. 如果您追求的是高精度,那么确实可以使用
BigDecimal
。
Use Double.parseDouble()
to do this... 使用
Double.parseDouble()
执行此操作...
String n1 = "1.123";
String n2 = "1.123E-4";
double dn1 = Double.parseDouble(n1);
double dn2 = Double.parseDouble(n2);
System.out.println("Total : " + (dn1 + dn2));
Output: 输出:
1.1231123
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.