pamiers
pamiers

Reputation: 355

How can i get sum in java?

I want to summation in java.

So,

For example,

1.123 + 1.123E-4 = 0.0123411234

So, How can i processing "E" in java?

Upvotes: 0

Views: 1828

Answers (5)

Kumar Vivek Mitra
Kumar Vivek Mitra

Reputation: 33534

Use Double.parseDouble() to do this...

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

Upvotes: 0

obataku
obataku

Reputation: 29646

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. If high-precision is what you're striving for, indeed use BigDecimal.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425033

Use 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

Upvotes: 2

user100464
user100464

Reputation: 18429

Use the BigDecimal class. 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".

Upvotes: 1

Jon Lin
Jon Lin

Reputation: 143886

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.

And actually, the result is: 1.1231123

Upvotes: 0

Related Questions