Jack Parker
Jack Parker

Reputation: 569

Converting Text Field to Numerical Value (Getting NaN)

I have this bit of code, it's supposed to take the value from one field, and calculate the value from it based on a certain percentage (in this case 60%).

I created a hidden field to store the value in the html, but when I run the calculation and check it in Firebug it gets a NaN value. Can anyone tell me what I can do to produce the number I need?

 (Apply_RequestedAmtX_r != 0 & Apply_RequestedAdvanceAmtY_r !=0){
    var AmtX= ($('#Apply_RequestedAdvanceAmtX_r').val());
    var AmtY= ($("#Apply_AmtYAfterSplit_r").val());
    var MaxAMT = parseInt((AmtY*60)/100);
        $('#mna').val(MaxAMT

Upvotes: 0

Views: 246

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074666

val returns a string. Now, the way you're using those variables, they'll get automagically converted to numbers (although it's best practice to parse them yourself).

One or the other of your values has a character in it that prevents the value from being automatically converted to a number; and then since that's NaN, any math involving it will be NaN. If you examine AmtX and AmyY in Firebug before using them, you should see whatever that character is.

Again, parsing isn't the actual problem here, but you're using parseInt in exactly the wrong place (unless you were trying to use it to truncate the fractional portion of the number, in which case there are better choices). Here are the right places:

var AmtX= parseInt($('#Apply_RequestedAdvanceAmtX_r').val(), 10);
var AmtY= parseInt($("#Apply_AmtYAfterSplit_r").val(), 10);
var MaxAMT = (AmtY*60)/100;

MaxAMT will likely have a fractional portion. If you want MaxAMT to be an integer, then:

var MaxAMT = Math.round((AmtY*60)/100);
// or
var MaxAMT = Math.floor(AmtY*60)/100);
// or
var MaxAMT = Math.ceil(AmtY*60)/100);

...depending on your needs.

Upvotes: 1

Related Questions