I have experience of VB and c# but not ST. Im trying to find the value of the nth digit in a value. ie 654321 the nth value when n = 3 should return 4. Is it possible to do this in ST?
Asked
Active
Viewed 130 times
1 Answers
0
I suggest to convert the number to STRING and then you can find the nth character from the string. Of course, you didn't tell that if your number 654321 is a string or number value, but it doesn't really matter.
The following code takes the 3rd character from the left. If you need to get the digit from right, you can edit the code using LEN() etc. functions.
VAR
TestNumber : DINT;
TestString : STRING;
NthDigitAsString : STRING(1);
NthDigit : BYTE;
END_VAR
TestNumber := 654321;
//Convert to string
TestString := DINT_TO_STRING(TestNumber);
//Find the 3rd character (counting from from left)
NthDigitAsString := MID(TestString, 1, 3);
//Convert the character to number (if necessary)
NthDigit := STRING_TO_BYTE(NthDigitAsString);
That is of course a long version. Find the one-liner below:
NthDigit := STRING_TO_BYTE(MID(DINT_TO_STRING(654321), 1, 3));

Quirzo
- 1,183
- 8
- 10