How to Convert Real Numbers from Scientific Notation to Decimal Strings in TwinCAT3?

How to Convert Real Numbers from Scientific Notation to Decimal Strings in TwinCAT3?



The following is the program code

FUNCTION ConvertScientificToDecimal : STRING VAR_INPUT num : LREAL; END_VAR VAR count : INT := 0; // Counter for multiplying by 10 until num >= 1 strNum : STRING; // String to hold the converted number strNumNoDot : STRING; // String without the decimal point iDotPos : INT; // Position of the decimal point dotIndex : INT; // Index of the decimal point i : INT; // Loop counter zeros : STRING; // String of zeros END_VAR IF ABS(num) < 1.0 THEN // Move the decimal point to the right until num >= 1 WHILE ABS(num) < 1.0 DO num := num * 10; count := count + 1; END_WHILE; // Convert num to a string strNum := LREAL_TO_STRING(num); // Remove the negative sign if present IF num < 0 THEN strNum := DELETE(strNum, 1, FIND(strNum, '-')); END_IF; // Find the position of the decimal point iDotPos := FIND(strNum, '.'); // Handle the case where there is a trailing zero after the decimal point IF (FIND(strNum, '.0') <> 0 AND (LEN(strNum) - iDotPos) = 1) THEN strNumNoDot := DELETE(strNum, 2, iDotPos); ELSE // Find the index of the decimal point dotIndex := FIND(strNum, '.'); // Remove the decimal point strNumNoDot := DELETE(strNum, dotIndex, 1); END_IF; // Build a string of zeros zeros := ''; FOR i := 1 TO count - 1 DO zeros := CONCAT(zeros, '0'); END_FOR; // Build the final string IF num > 0 THEN strNum := CONCAT('0.', CONCAT(zeros, strNumNoDot)); ELSIF num < 0 THEN strNum := CONCAT('-0.', CONCAT(zeros, strNumNoDot)); ELSE strNum := '0'; END_IF; ELSE // If num is already >= 1, convert it directly to a string strNum := LREAL_TO_STRING(num); END_IF; // Return the final string ConvertScientificToDecimal := strNum;