Actually, I get this problem in Gnuplot. But in a simple way, the problem is I want to use sprintf to print in string format, even though the string consists of numbers and symbol. Like this:
a = '12/7'
sprintf('%.f', a)
I am able to run it in Gnuplot, but it only shows numbers before symbol "/". I expect the output should print all the content of variable a
which is '12/7'. Any suggestion for this case?
If you are referring to the sprintf
built-in function in gnuplot
, the documentation help sprintf
says:
sprintf("format",var1,var2,...)
applies standard C-language format specifiers to multiple arguments and returns the resulting string. If you want to use gnuplot's own format specifiers, you must instead callgprintf()
. For information on sprintf format specifiers, please see standard C-language documentation or the unix sprintf man page.
In the Unix man page for %f
says (truncated):
%f, %F -- The double argument is rounded and converted to decimal notation in the style [-]ddd.ddd, where the number of digits after the decimal-point character is equal to the precision specification.
Hence, you need to use a different format specifier. As fedorqui pointed out the appropriate format specifier is %s
.
I often refer to the table in this link for looking up the appropriate format specifiers (I find the C man page a bit long).
Using sprintf
with strings from files
In order to use sprintf
to format a string from a file, you need to specify the column in the file to extract the string information from. This needs to be done using the stringcolumn
command instead of just using a $
sign.
For example, if you wanted to include a number from a file you might use a command like:
plot "data.dat" using 1:2:(sprintf('%f', $3)) with labels
But for a string you need:
plot "data.dat" using 1:2:(sprintf('%s', stringcolumn(3))) with labels
When you say
$ awk 'BEGIN {a="12/7"; printf "%.f", a}'
12
You get the int part of the number, because by using a f
flag in printf you are casting it to a number instead of a string. So it is equivalent to saying:
awk 'BEGIN {a="12/7"; a=int(a); print a}'
If you want to keep all of it, use %s
for string:
$ awk 'BEGIN {printf "%s", "234-456"}'
234-456
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With