The following examples demonstrate conversion of numeric variables to string, including notation to format the number of digits and decimal places.
To convert a variable of a numeric type (double, int, or const) to a variable of string type, consider the following simple example:
// myNum contains the integer value 456 int myNum = 456; // myNumString now contains the characters 456 as a string string myNumString$ = $(myNum);
The syntax $(num) is one of type of substitution notation supported in LabTalk. Another, %(string$), is used to convert in the opposite direction, from string to numeric, substituting a string variable with its content.
Formatting can also be specified during the type conversion:
$(number [,format]) // braces indicate that the format is optional
Format follows the C-programming format-specifier conventions, which can be found in any C-language reference, for example:
string myNumString2$ = $("3.14159",%3d); myNumString2$= // "3" string myNumString2$ = $("3.14159",%3.2f); myNumString2$= // "3.14" string myNumString2$ = $("3141.59",%6.4e); myNumString2$= // "3.1416e+003"
For further information on this type of formatting, please see $() Substitution.
Another way to convert a numeric variable to a string variable uses the format function:
// call format, specifying 3 significant figures string yy$=Format(2.01232, "*3")$; // "2.01" yy$=;
For full documentation of the format function see Format (Function)
LabTalk has native format specifiers that, used as part of LabTalk's Substitution Notation provide a simple means to format a number.
x = 1.23456; type "x = $(x, *2)";
In this example, x is followed by "*2", which sets x to display two significant digits. So the output result is:
x = 1.2
Additionally, putting a "*" after "*n" will remove trailing 0's before the power of ten. For instance,
y = 1.10001; type "y = $(y, *4*)";
In this example, the output result is:
y = 1.1
The result has only 2 siginificant digits, because y is followed by *4* instead of *4.
double x = 1.23456; type "x = $(x, .2)";
In this example, x is followed by ".2" which sets x to display two decimal places. So the output result is:
x = 1.23
Additionally, putting a "," after ".n" will show thousand separator
double x = 12345678.9; type "x = $(x, .0,)";
The output will show 0 decimal places and thousand separator
x = 12,345,679
The E notation follows the variable it modifies, like the * notation. For example,
x = 1e6; type "x = $(x, E%4.2f)";
where % indicates the start of the substitution notation, 4 specifies the total number of digits, .2 specifies 2 decimal places, and f is an indicator for floating notation. So the output is:
x = 1.00M
In this syntax, n specifies the total number of digits.
x = 1.23456; type "x = $(x,S*3)";
And Origin returns:
x = 1.23E0