How to convert variable 'single line text' in an integer?

davide_fais
Tera Expert

Hi ServiceNow Community,

I've a variable type 'single line text' and I'd like convert this in a integer value, for exampe:

var number=g_form.getValue('u_variable_number');

if (number > 10)

number ++

etc

How can I do this?

Thanks,

Best Regards.

1 ACCEPTED SOLUTION

drjohnchun
Tera Guru

If you decide to use the parseInt() function, best practice is to specify the second parameter for radix, which is 10 for the decimal system. You might end up with unexpected results if you omit it, as it says in parseInt() - JavaScript | MDN:



If radix is undefined or 0 (or absent), JavaScript assumes the following:


  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
  • If the input string begins with "0", radix is eight (octal) or 10 (decimal).   Exactly which radix is chosen is implementation-dependent.   ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.   For this reason always specify a radix when using parseInt.
  • If the input string begins with any other value, the radix is 10 (decimal).

If the first character cannot be converted to a number, parseInt returns NaN.



Hope this helps.



Please feel free to connect, follow, mark helpful / answer, like, endorse.


John Chun, PhD PMP see John's LinkedIn profile

visit snowaid


ServiceNow Advocate

View solution in original post

5 REPLIES 5

Patrick Fedigan
Giga Guru

Hello Davide,



You can use the parseInt(""); function to have a string return an integer



For example


var number = g_form.getValue('u_variable_number');


var number = parseInt(number);



if(number > 10) {


        number++;


}


Hi Davide,



Just to modify the code,



  1. var val= g_form.getValue('u_variable_number');  
  2. var number = parseInt(val);  
  3.  
  4. if(number > 10) {  
  5.         number++;  
  6. }  

Should be used



Regards,


Shariq


mark helpful if it helps


BALAJI40
Mega Sage

Try this one


var number=g_form.getIntValue('u_variable_number');



if (number > 10)


number ++


etc


randrews
Tera Guru

converting a single line text to an integer is generally a bad idea.. when you find an A for example is that the number 10 <in base 16> or is it the letter A? .. hard to tell and harder to program around.. while the solutions given will work i would strongly suggest you retire that field from the form by unchecking active and add a NEW integer field that you can use for this purpose...



then, if required, write a background script to back-fill this field from the existing single line text field.