tags:

views:

14

answers:

3

Hi,

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(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

+1  A: 

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);
softcr
+1  A: 

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).

T.J. Crowder
Your point is right.But what if i want to use toFixed and return a float number.In my case i have already 2 decimal point, but if i had 4 decimals i had to convert to float with 2 decimal points.
ntan
@ntan: You could always do `parseFloat(parseFloat(xxx).toFixed(2))` (I forget what guarantees the standard makes about whether `toFixed` does half-up rounding or just truncates; I think it does half-up rounding), but you might be better off explicitly rounding the numbers. Sadly, `Math.round` can only round to integer values, but it's easy enough to build on that to create floating-point rounding: http://www.javascriptkit.com/javatutors/round.shtml
T.J. Crowder
+1  A: 

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.

naivists