1

I'm trying to add two values together e.g. 14.0 + 2.1 = 16.1 but I keep on getting them added onto each other e.g 14.0 + 2.1 = 14.02.1

var miledistance = miledistance1 + miledistance2;
3
  • 3
    It's obviously Javascript and not Java. Commented Jun 22, 2011 at 15:02
  • Perhaps you are using Javascript which is not the same as Java. Commented Jun 22, 2011 at 15:02
  • 1/ javascript, not java 2/ to add vs. to concatenate Commented Jun 22, 2011 at 15:02

2 Answers 2

10

For Java:

Make sure they are both float values.
Try casting:

miledistance = (float) miledistance1 + (float) miledistance2;

Or use Float.valueOf():

miledistance = Float.valueOf(miledistance1) + Float.valueOf(miledistance2);

For Javascript:

miledistance = parseFloat(miledistance1) + parseFloat(miledistance2);

NOTE: Java and javascript are not the same language.

Sign up to request clarification or add additional context in comments.

1 Comment

OPs problem looks like string concatenation; could you change the Java example to something parsing the string (say, Float.valueOf(...) instead of the cast)?
1

It seems to be that the program is treating them as strings, cast them as float or double.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.