sprintf

Formats data into text with a format specification.

Category: Language Fundamentals > Data Types

Syntax

str = sprintf(formatSpec, A1, ..., An)

Formats the arguments according to formatSpec and returns a character vector.

Description

The format is reused as many times as needed to use up all arguments, so sprintf('%d,', [1 2 3]) gives '1,2,3,'. Escape sequences such as \n and \t in the format are translated. Matrix arguments are read down the columns.

A %d conversion given a non-integer value switches to exponent notation (sprintf('%d', 2.5) gives '2.500000e+00'). Use %s with a string scalar, and fprintf to print the same text directly.

Input arguments

formatSpec
Text with plain characters and conversions such as %d (integer), %f (fixed), %e (exponent), %g (shorter of the two), %s (text), %c (character), %x (hexadecimal). Flags, width and precision go between % and the letter, as in %8.3f or %-6d.
A1, ..., An
Values to insert, consumed in column order.

Output arguments

str
Character vector with the formatted text.

Example

sprintf('%d items, %5.2f', 3, 2.5)
sprintf('%d,', [1 2 3])
sprintf('%6.2f|%-6d|%e', pi, 5, 12345.678)
sprintf('%x', 255)
Output
ans = '3 items,  2.50'
ans = '1,2,3,'
ans = '  3.14|5     |1.234568e+04'
ans = 'ff'

See also

fprintf num2str disp string sscanf compose