Naveen Dennis
Naveen Dennis

Reputation: 1223

Passing the output of a statement to a statement in Octave. Why does sprintf modify data?

I would like to understand the following behavior of Octave.

How does sprintf work?

When padding a floating point number with 10 digits:

$ ans = 2;
$ sprintf('%10.3f',ans)
ans =      2.000
$ sprintf('%10.3f',ans)
ans =     32.000    32.000    32.000    32.000    32.000    50.000    46.000    48.000    48.000    48.000

When passing a floating point with precision of 3 decimal digits:

$ ans = 2
ans =  2
$ sprintf('%0.3f',ans)
ans = 2.000
$ sprintf('%0.3f',ans)
ans = 50.00046.00048.00048.00048.000

When passing an integer:

$ ans = 2
ans =  2
$ sprintf('%d',ans)
ans = 2
$ sprintf('%d',ans)
ans = 50

Why does that value of ans change when passing to sprintf? Shouldn't it just pass a formatted output without modifying the data?

Upvotes: 1

Views: 230

Answers (1)

Dan
Dan

Reputation: 45752

ans is just a place holder for the result of the most recently run command. The issue here is thatsprintf returns a string, not an integer or a float. So when you call

$ sprintf('%d',ans)
ans = 2

ans is acutally the character '2' which has an ASCII value of 50 and your next call specifically tells sprintf to consider the input as an integer hence it outputs 50. Try this instead:

$ sprintf('%d',ans)
ans = 2
$ sprintf('%s',ans) % i.e. tell sprintf to expect a string (%s) and not an integer (%d)
ans = 2

So considering another example from your question:

$ ans = 2
ans =  2
$ sprintf('%0.3f',ans)
ans = 2.000
$ sprintf('%0.3f',ans)
ans = 50.00046.00048.00048.00048.000

now the second call to sprintf is equivalent to sprintf('%0.3f','2.000') and if you cast the string 2.000 to integers you'll get [50, 46, 48, 48, 48]. You can prove this to yourself by typing uint8('2.000') in the command line.

Upvotes: 1

Related Questions