AMPScript/GTL function to check if variable is string or a numeric

Need to check a type of variable in ampscript, in order to use FormatNumber function(that can only work with integer variables).
I tried the Handlebars function {{isString()}}, but can’t make it worked with AmpScript or GTL, in code snippet block

SET @X  =  TreatAsContent('{{=isString(TrackingNumber )}}')     
     If @X == False THEN
         set @TrackingNumber = TreatAsContent('{{=FormatNumber(TrackingNumber, "d6")}}') 
     Else 
         set @TrackingNumber = TreatAsContent('{{TrackingNumber}}')   EndIF

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I think you can also accomplish your use case with format() as opposed to formatnumber()

I believe this fits your use case

%%[ 
 set @tn1 = '012345'
 set @tn2 = '01234a'
 set @tn3 = '123456'
]%%

%%=Format(@tn1, "0#####")=%%<br>
%%=Format(@tn2, "0#####")=%%<br>
%%=Format(@tn3, "0#####")=%%<br>

Provides the following values

012345
01234a
123456

Method 2

You aren’t going to have much luck checking the type with ampscript (or converting string to int without a hacky workaround if at all). Can you just pass that ampscript variable into SSJS to determine type and format the value there (or pass back to ampscript to format there)?

You can get and set the value with:

Platform.Variable.GetValue("@tracking_number");
Platform.Variable.SetValue("@formatted_tracking_number", var_you_format_in_ssjs);

That being said, I would highly advise that you just format your JSON string at the beginning of the email to convert the data type for all objects that contain a string value for this key. It would be much more efficient than checking the type of every tracking number when you call it in the email, and would be much easier to maintain.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x