Fsharp: Format String

By Xah Lee. Date: . Last updated: .

The functions printf printfn sprintf first argument is a string, with placeholders. Placeholders is 2 characters starting with %.

sprintf turns values into a string, but does not print.

// print 3 different values
printfn "integer %d, string %s, boolean %b" 3 "abc" true
// integer 3, string abc, boolean true

// print a tuple
printfn "integer %A" (3, "abc", true)
// turn values into a string
let xx = sprintf "%d %s %b" 3 "abc" true
printfn "%s" xx
// 3 abc true
Format specifierType(s)Remarks
%bbool (System.Boolean)Formatted as true or false
%sstring (System.String)Formatted as its unescaped contents
%cchar (System.Char)Formatted as the character literal
%d, %ia basic integer typeFormatted as a decimal integer, signed if the basic integer type is signed
%ua basic integer typeFormatted as an unsigned decimal integer
%x, %Xa basic integer typeFormatted as an unsigned hexadecimal number (a-f or A-F for hex digits respectively)
%oa basic integer typeFormatted as an unsigned octal number
%Ba basic integer typeFormatted as an unsigned binary number
%e, %Ea basic floating point typeFormatted as a signed value having the form [-]d.dddde[sign]ddd where d is a single decimal digit, dddd is one or more decimal digits, ddd is exactly three decimal digits, and sign is + or -
%f, %Fa basic floating point typeFormatted as a signed value having the form [-]dddd.dddd, where dddd is one or more decimal digits. The number of digits before the decimal point depends on the magnitude of the number, and the number of digits after the decimal point depends on the requested precision.
%g, %Ga basic floating point typeFormatted using as a signed value printed in %f or %e format, whichever is more compact for the given value and precision.
%Ma decimal (System.Decimal) valueFormatted using the "G" format specifier for System.Decimal.ToString(format)
%Oany valueFormatted by boxing the object and calling its System.Object.ToString() method
%Aany valueFormatted using structured plain text formatting with the default layout settings
%aany valueRequires two arguments: a formatting function accepting a context parameter and the value, and the particular value to print
%tany valueRequires one argument: a formatting function accepting a context parameter that either outputs or returns the appropriate text
%%(none)Requires no arguments and prints a plain percent sign: %

Reference

Fsharp, String