Ruby - String printf Format

Introduction

Ruby printf method can output "format strings" containing specifiers starting with a percent sign (%).

The format string may be followed by one or more data items separated by commas.

The list of data items should match the number and type of the format specifiers.

The actual data items replace the matching specifiers in the string, and they are formatted accordingly.

These are some common formatting specifiers:

Item Description
%d decimal number
%f floating-point number
%o octal number
%p inspect object
%s string
%x hexadecimal number

You can control floating-point precision by putting a point-number before the floating-point formatting specifier, %f.

For example, this would display the floating-point value to six digits (the default) followed by a carriage return ("\n"):

Demo

printf( "%f\n", 10.12945 )        #=> 10.129450

Result

The following would display the floating-point value to two digits ("%0.02f").

Demo

printf( "%0.02f\n", 10.12945 )     #=> 10.13 
printf("d=%d f=%f o=%o x=%x s=%s\n", 10, 10, 10, 10, 10) 
printf("0.04f=%0.04f : 0.02f=%0.02f\n", 10.12945, 10.12945)

Result

Related Topic