1

in the JavaScript I am trying to implement for my aspx page, parsefloat("-2.00') is returning a value 0-2.00

Obviously there is something I am missing out, because parsefloat can handle negative numbers, however, here it is showing me this value in debugging and output is coming out to be 0.

Please help me look into what I may be doing wrong.

The code I am using in the javascript

var A=0;
A = document.getElementById('A').value;
A += (parseFloat(A).toFixed(2));
document.getElementById("C").value = roundToTwo(parseFloat(A) + parseFloat(B));

Thanks

Sverri M. Olsen
  • 13,055
  • 3
  • 36
  • 52

2 Answers2

2

UPDATE

See documentation for .toFixed() - it returns a string representation of that number.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed

What you need to do is to split adding two numbers and calling toFixed. Like this

 var A=0; //A is of type number
 A = document.getElementById('A').value; //A is of type string
 A += parseFloat(A); //A is of type number again
 A = A.toFixed(2); //A is of type string again

When you call += on two variables, where one is number and the other is string, then both will be cast to string and simply appended.

David Votrubec
  • 3,968
  • 3
  • 33
  • 44
1

The problem is that when you're getting the value of the HTML element with id A, you're getting a String value. Because you're trying to add a float to a string, your flaot will be automatically converted to a string and therefore concatenanted.

Ensuring A is always a float should solve this issue.

A = parseFloat(document.getElementById('A').value);
A += parseFloat(parseFloat(A).toFixed(2));
dmlittle
  • 964
  • 6
  • 15