indi60
indi60

Reputation: 907

Using sprintf to print string value

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?

Upvotes: 8

Views: 23048

Answers (3)

shahb0z
shahb0z

Reputation: 73

You can multiply by floating-point number and use that as following: sprintf('%.f', a*1.0)

In this way, you force gnuplot to treat a as floating-point number.

Upvotes: 0

ilent2
ilent2

Reputation: 5241

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 call gprintf(). 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

Upvotes: 9

fedorqui
fedorqui

Reputation: 290075

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

Upvotes: 3

Related Questions