I have the code above:
var element1=$("#element1").val();
//the element1 value is 12.60
//html code for this element <input id="element1" value="12.60" />
element1=parseFloat开发者_JS百科(element1).toFixed(2);
var element2=$("#element2").text();
//the element2 value is 1.00
//html code for this element <span id="element2">1.00</span>
element2=parseFloat(element2).toFixed(2);
var addthem=element1+element2;
console.log(addthem);
And of course I am expecting to see 13.60
but I get 12.601.00
(add the as string).
Am I missing something?
parseFloat
is working fine, but then you're explicitly getting a string version of the values (via toFixed
), and so +
concatenates the strings. Only use toFixed
at the point you want to convert the numbers to a string (for instance, to output to an element).
A quick check with Firebug, shows that the toFixed() method returns a string in Firefox:
var f = 16.055;
console.log(typeof(f.toFixed(1)));
returns: string
Thus you should change the second last line to:
var addthem = parseFloat(element1) + parseFloat(element2);
toFixed()
, i believe, returns a String as its datatype.
The +
operator you use in var addthem=element1+element2;
works as string concatenation, since +
is overloaded in JavaScript. If any of the operands is a string, a string value is returned.
精彩评论