sam
sam

Reputation: 37

How can i add two double values without exponential in android

Please help me to solve this. I trying to get value from textview and stored as string. Then it converts to double. While converting up to 7 characters functioning normally but if i try to add more than 7 result is 1.23456789E8. Here is my code

String value = tvInput.getText().toString();
\\tvInput is my textView
Double result = 0.0;
Double input1=0.0;
Double input2=0.0;
input=Double.parseDouble(value);
result = input1 + input2;
tvInput.setText(Double.toString(result));

if i give input1 value as 1234567 and input2 as 1234567 i am getting correct result but if give input1 as 12345678 and input2 as 3. the output is 1.2345681E7

Upvotes: 3

Views: 7607

Answers (5)

neciu
neciu

Reputation: 4485

Use String.format: example

class Main
{
  public static void main (String[] args) throws java.lang.Exception
  {
     String i1 = "12345678";
     String i2 = "3";
     double d1 = Double.parseDouble(i1);
     double d2 = Double.parseDouble(i2);
     double d = d1 + d2;
     System.out.println( String.format("%f", d) ); 
  }
}

Upvotes: 0

SJuan76
SJuan76

Reputation: 24885

Either 12345678 and 1.2345678E7 are exactly the same number. No trouble with that

Your trouble is with the representation, if E>6 then toString() use scientific notation. You may want to use NumberFormat for this.

Upvotes: 0

Ishtar
Ishtar

Reputation: 11662

Why don't use Integer instead?

String value = tvInput.getText().toString();
\\tvInput is my textView
int result = 0;
int input1 = 0;
int input2 = 0;
input=Integer.parseInt(value);
result = input1 + input2;
tvInput.setText(Integer.toString(result));

Upvotes: -2

assylias
assylias

Reputation: 328649

The behavior you describe is consistent with the javadoc. You could use String.format instead.

Upvotes: 0

Joeri Hendrickx
Joeri Hendrickx

Reputation: 17445

The value you get is correct, the issue is with the way you print it.

You're relying on toString for a double output; if you want to guarantee not to have an exponential notation, you should format it using a DecimalFormat, or with String.format;

DecimalFormat myFormatter = new DecimalFormat("############");
tvInput.setText(myFormatter.format(result));

Also see the format documentation

Upvotes: 3

Related Questions