This is part of 3.33.0latest release.

REAL_TO_STRF

1.8.0
since lib: v0.13.0  

`REAL_TO_STRF` converts a REAL value to a string with a fixed number of decimals.

REAL_TO_STRF converts a REAL value to a string with a fixed number of decimals.

Examples:

REAL_TO_STRF(3.14159, 4, '.')   // '3.1416'
REAL_TO_STRF(3.14159, 0, '.')   // '3'
REAL_TO_STRF(0.04159, 3, '.')   // '0.042'
REAL_TO_STRF(0.001, 2, ',')     // '0,00'

Version history

1.8.0

  hm

Changes

Added:
  • input parameter D to specify decimal separator
show full history

1.7.0

  hm

Changes

Changed:
  • added missing zero for IN < 1

1.6.0

  hm

Changes

Added:
  • added variable O to avoid an error under CoDeSys SP PLCWinNT V2.4

1.5.0

  hm

Changes

Changed:
  • changed STRING to STRING(20)

1.4.0

  hm

Changes

Changed:
  • changed trunc to real_to_dint because trunc was generating wrong values on wago 842

1.3.0

  hm

Changes

Changed:
  • result is now rounded instead of truncated

1.2.0

  hm

Changes

Changed:
  • changed code for better performance

1.1.0

  hm

Changes

Changed:
  • when N = 0 there will be no dot at the end of the string

1.0.0

  hm

Changes

Added:
  • original version

Overview

kindnametypedefaultcomment
inputINREALinput value
inputNINTnumber of decimal places
inputDSTRING(1)decimal punctuation character

Details

IN

REAL

Input value.

N

INT

Number of decimal places.

valueexplanation
0..7range for N

D

STRING(1)

Decimal punctuation character. Depending on your country/region this usually is either a dot (.) or a comma (,).

Source code

Declarations

(*Converts a Real to a fixed length String*)
FUNCTION index : STRING(20)

(*
 * -----------------------------------------------------------------------------
 * Name               : index
 * Version            : 1.8.0
 * Date               : 2012-01-02
 * Author             : hm
 * 
 * -----------------------------------------------------------------------------
 * Converts a Real to a fixed length String
 * -----------------------------------------------------------------------------
 *)

VAR_INPUT
  IN : REAL; (*input value*)
  N : INT; (*number of decimal places*)
  D : STRING(1); (*decimal punctuation character*)
END_VAR

VAR
  O : REAL;
  i : INT;
END_VAR

Logic

(* LIMIT N to 0 .. 7 *)
N := LIMIT(0,N,7);

(* round the input to N digits and convert to string *)
O := ABS(in) * EXP10(N);
REAL_TO_STRF := DINT_TO_STRING(REAL_TO_DINT(O));

(* add zeroes in front to make sure sting is at least 8 digits long *)
FOR i := LEN(REAL_TO_STRF) TO N DO
  REAL_TO_STRF := CONCAT('0', REAL_TO_STRF);
END_FOR;

(* add a dot if n > 0 *)
IF n > 0 THEN
  REAL_TO_STRF := INSERT(REAL_TO_STRF, '.', LEN(REAL_TO_STRF) - N);
END_IF;

(* add a minus sign if in is negative *)
IF in < 0 THEN
  REAL_TO_STRF := CONCAT('-', REAL_TO_STRF);
END_IF;

Implementation

Snippet of the function call:
dummy := REAL_TO_STRF(
           IN := ,
           N := ,
           D := );