In Sage X3, converting string data into numeric values is a common requirement—especially when working with imported data, user inputs, or web services. The val() function makes this conversion simple and efficient. In this blog post, we’ll walk through how to use the val() function, handle invalid inputs, and perform basic arithmetic operations with it.
What is the val() Function?
The val() function is a built-in function in Sage X3 that allows you to convert a string (Char) into a numeric value. You can then use that value for calculations or comparisons.
Example 1: Convert a Valid String to Integer and Perform Calculations
In this example, we’ll convert a valid numeric string to an integer and multiply it by 5.
Code:
## Variables
Local Char NumStr : NumStr = “2”
Local Integer NumInt : NumInt = 0
## Convert string to integer
NumInt = val(NumStr) * 5
## Print the result
Infbox “The result is: ” + NumStr + ” * 5 = ” + num$(NumInt)
Output:
The result is: 2 * 5 = 10
In this example:
1.We defined a string variable NumStr with the value “2”
2.We converted it to an integer using val(NumStr)
3.We multiplied the result by 5
4.Finally, we displayed the result using Infbox
New Stuff:- Custom Field Entry Without Sales Invoice Access in Sage X3
What Happens with Invalid Strings?
If the string contains non-numeric characters, the val() function will return 0.
Example with Invalid Input:
## Variables
Local Char NumStr : NumStr = “str2”
Local Integer NumInt : NumInt = 0
## Convert string to integer
NumInt = val(NumStr) * 5
## Print the result
Infbox “The result is: ” + NumStr + ” * 5 = ” + num$(NumInt)
Output:
The result is: str2 * 5 = 0
Here, since the string starts with alphabetic characters, the conversion fails and returns 0.
What If the String Starts with a Number?
If the string starts with a numeric character followed by text, val() will extract and convert only the leading numeric part.
Example with Mixed Input:
## Variables
Local Char NumStr : NumStr = “2str2”
Local Integer NumInt : NumInt = 0
## Convert string to integer
NumInt = val(NumStr) * 5
## Print the result
Infbox “The result is: ” + NumStr + ” * 5 = ” + num$(NumInt)
Output:
The result is: 2str2 * 5 = 10
Here, only the first numeric part (2) is considered, and the rest is ignored.
If you’re working with decimal numbers (e.g., “3.14”), make sure to use a Decimal or Real variable to store the result. If you use an Integer, the decimal portion will be truncated.
Code:
Local Char NumStr : NumStr = “3.14”
Local Decimal NumDecimal : NumDecimal = 0.0
NumDecimal = val(NumStr)
In Sage X3, this is how we convert a string (char) to an integer or decimal value.
[about_us_blog_common]