Skip to main content
SSCSteven
Participating Frequently
March 2, 2018
Question

JavaScript for Convert String to Number

  • March 2, 2018
  • 1 reply
  • 18298 views

Hello

I have a concatenated field with custom script below:

var s1 = this.getField("Leave Yard Hour").valueAsString; 

var s2 = this.getField("Leave Yard Minutes").valueAsString;  

// Set this field value by concatenating the field values 

event.value = s1 + "." + s2; 

-------------------------------------------

Then in another field - I'm trying to parse it into an integer and then do a calculation for the difference using the below but it is not working:

// Get first field value

var v1 = getField("Leave Yard Total").value;

var v1 = parseInt("Leave Yard Total")

// Get second field value

var v2 = getField("Arrive Job Total").value;

var v2 = parseInt("Arrive Job Total")

// Set this field value equal to the difference

event.value = v2 - v1;

------------------------------------------------------------------

any help is greatly appreciated

This topic has been closed for replies.

1 reply

Thom Parker
Community Expert
Community Expert
March 2, 2018

parseInt isn't going to help if the number is a decimal   But just for your information, the input to this function is a number string.

For example: parseInt("3");

But it is much easier than this to convert a string to a number in JavaScript. Just cast it as a number

EX: 

var v2 = Number(getField("Arrive Job Total").value);

But the fact is that event this is unnecessary because the casting is automatic when you use a value in an obvious number calculation.  Your script will work if you just delete the lines with "parseInt".

The best way to test out these scripting ideas is to use the console window. You'll save yourself huge amounts of time and frustration by using it. Here's a video tutorial: The Acrobat JavaScript Console Window - YouTube

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
SSCSteven
SSCStevenAuthor
Participating Frequently
March 2, 2018

I tried it without the parse and without the decimal. It returns NaN.

I also tried your example and it still returns NaN.

Thom Parker
Community Expert
Community Expert
March 2, 2018

What I told you works 100%. So, if it's returning NaN that means that the field value is not a number. So did you check to see what the value is that is being returned from the field?

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often