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;
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;
Share
Improve this question
edited Dec 8, 2013 at 4:45
Josh Crozier
241k56 gold badges400 silver badges313 bronze badges
asked Jun 22, 2011 at 15:00
sw2020sw2020
1951 gold badge2 silver badges10 bronze badges
3
- 3 It's obviously Javascript and not Java. – Fabian Barney Commented Jun 22, 2011 at 15:02
- Perhaps you are using Javascript which is not the same as Java. – Peter Lawrey Commented Jun 22, 2011 at 15:02
- 1/ javascript, not java 2/ to add vs. to concatenate – Rostislav Matl Commented Jun 22, 2011 at 15:02
2 Answers
Reset to default 10For 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.
It seems to be that the program is treating them as strings, cast them as float or double.