val(
VALUE
,
DECIMALPOINT
)

The val( function converts text into a number.

Parameters

This function has two parameters:

value – text to be converted to a numeric value.

decimalpoint – decimal point character, either period or comma. If this parameter is omitted, the decimal point specified by the system’s Languages & Region panel will be used.

Description

The val( function converts text to a number, assuming of course that the text contains a numeric value. If the text contains a decimal point or exponent, the resulting value is floating point, otherwise it is an integer. If the text doesn’t contain a recognizable number, the result is an integer zero.

The val( function can also be used with a numeric parameter, in which case it simply passes the numeric value along. This can be handy when you don’t know for sure if a field or variable will contain text or a number.

Here are some examples of the val( function in operation:

``````val("72") ☞ 72
val("72.95") ☞ 72.95
val("2e3") ☞ 2000
val("  98  ") ☞ 98 // whitespace is ignored
val("abc") ☞ 0
val("234Z") ☞ 234 // non-digits at the end are ok
val("po234") ☞ 0 // but not at the beginning
``````

If your text might contain non-digit characters you can use the striptonum( function to eliminate them.

``````val(striptonum("po234")) ☞ 234
``````

If you are using floating point numbers, use the stripchar( function like this.

``````val(stripchar("ZED 387.38","--09..")) ☞ 387.38
``````

### Decimal Point Regional Settings (Period vs. Comma)

Some countries use a period to specify the decimal point in numeric values, other countries use a comma. The val( function will normally use whatever character is specified by the Languages & Regions panel in Apple’s System Preferences window.

In some situations, you may want to explicitly specify what decimal point to use, independent of the Languages & Regions panel. To do this, add a second parameter to the val( function specifying the decimal point character, like this:

``````let pi = "3.14159"
let circumference = radius * 2 * val(pi,".")
``````

Or, like this:

``````let pi = "3,14159"
let circumference = radius * 2 * val(pi,",")
``````

Of course, these are silly examples because you might as well use

``````let circumference = radius * 2 * 3.14159
``````

or even:

``````let circumference = radius * 2 * π
``````

But the point is that if you have text that contains a particular decimal point, using the second parameter will allow this text to be converted into a number correctly no matter what the Languages & Regions setting is.