最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript Adding Values Together - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 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.

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

发布评论

评论列表(0)

  1. 暂无评论