Floating point number conversion

Floating point number conversion 1:

Undefined result if the value range is exceeded

If the input value of a type conversion operator is outside the value range of the output data type, the result of the operation is not defined and depends on the platform. This is the case, for example, when a negative operand value is converted from LREAL to the target data type UINT. An exception error is also possible!

Floating point number conversion 2:

Loss of information possible

If a larger data type is converted to a smaller data type, information may be lost.

Floating point number conversion 3:

If the floating point number is within the value range of the target data type, the conversion works the same on all systems.

If the floating point number exceeds the range limit, the first bytes of the number are not taken into account.

Floating point number conversion 4:

Rounding logic

The rounding logic for borderline cases depends on the target system or the FPU (Floating Point Unit) of the target system. For example, a value like -1.5 may be converted differently on different controllers.

Intercept value range overflows through the application to program target system-independent code.

<type>_TO_REAL / <type>_TO_LREAL

The operators are used to convert from another data type to the REAL or LREAL data type.

You can specify a variable or a literal as the operand.

Rounding is performed during conversion if necessary.

Syntax:

<Datentyp>_TO_REAL (<Variablenname> | <Literal>)
<Datentyp>_TO_LREAL (<Variablenname> | <Literal>)

REAL_TO_<type> / LREAL_TO_<type>

The operators are used to convert the data type REAL or LREAL to another data type.

You can specify a variable or a literal as the operand.

Syntax:

REAL_TO_<Datentyp> (<Variablenname> | <Literal>)
LREAL_TO_<Datentyp> (<Variablenname> | <Literal>)

Rounding:

TwinCAT rounds the floating point value of the operand up or down to an integer value and converts this to the corresponding data type. Round down for 1 to 4 after the point, round up for 5 to 9. The data types STRING, BOOL, REAL, and LREAL are excluded from this rounding.

Convert to a string:

When converting a floating point number to a string, the number of decimal places of the mantissa is limited to 6. If the number is < 1, the following applies to the mantissa m: 1 <= m < 10. If the mantissa has more digits after the decimal point, it is rounded to the 6th digit and then converted.

In addition, the string variable for the return value may be declared too short. The return string is then truncated on the right.

Examples:

ST code

Result

nVar1 := REAL_TO_INT(1.5);

2

nVar2 := REAL_TO_INT(1.4);

1

nVar1 := REAL_TO_INT(-1.5);

-2

nVar2 := REAL_TO_INT(-1.4);

-1

FBD code

Result

Floating point number conversion 5:

2

See also: