Casting String to Integer with Expression

If I have an OPC tag that returns a string and I would like to convert it to an integer then what is the expression statement to do this? For example, if the strings look like any one of these:

0.0?
125.0?
99.5?

I would like to convert them to the following float values

0.0
125.0
99.5

The ‘?’ is part of what the device returns. I used the replace function to remove the ‘?.’ I used the replace function to remove the ‘.’ and then cast it to integer and float but I get an evaluation error. The evaluation error goes away when I cast to string but all I get are '‘00’, ‘1250’, and ‘995’

toFloat doesn’t work?

Same issue. I even have the tag data type as a Float or an Integer.

Here is the expression

toFloat(replace(replace({[~]Tag},’?’,’’), ‘.’,’’))

Where {[~]Tag} is a string that equals ‘0.0?’

Both of these work for me:
replace({[~]StringTag.value}, '?', '')
toFloat(replace({[~]StringTag.value}, '?', ''))

The first one gets implicitly cast to a float if the expression tag is configured as a Float.

1 Like

You should only need one replace operation, if you want to keep the decimal precision in the output:
toFloat(replace({[~]exp/WriteableString1}, "?", ""))
image

Here is the issue. The string came from an OPC tag and defaulted to 5 characters. In order to convert the value to a float value I needed to trim the excess characters. Here is the final expression:

toFloat(replace(trim({[~]Tag}),"?",""))

Thanks for helping!

1 Like