Formatting parameters

There are essentially four formatting parameters available. They are listed in the following table:

Parameter

Use

Fill/Alignment

Used in conjunction with the Width parameter. Essentially, this will add extra characters if the output is smaller than the width.

Sign/#/0

Flags for the formatter being used:

  • Sign indicates that the sign should always be outputted (numeric values only). If the value is positive, the + sign will never show; similarly, a - will only show for a Signed value.
  • # indicates that an alternate form of printing will be used. Normally, if {:x} is used, the lowercase hex format is used. By using #x, the argument is preceded with 0x.
  • 0 is used to pad a result with the 0 character. It is sign-aware.

Width

Specifies how the output should be represented. For example, if you have a float calculation that has to be outputted to four decimal places, and the result only comes to two decimal places, the width formatter (in conjunction with the fill formatting parameter) will create the required filled output.

Precision

For anything non-numeric, the precision is the maximum width. For example, if you have a maximum width of five and a string containing eight characters, it will be truncated after five characters. It is ignored for integers. For floating point types, it indicates the number of decimal points after the point:

 

  • Integer .N:: In this case, N is the precision.
  • Integer followed by a $ (.N$:): This uses the format argument N as the precision. The argument must be a usize.
  • .*:: This means that the contents of the {} is associated with two format inputs. The first holds the usize precision, the second holds the value to be printed.

 

Examples of all of these formatters are in the source code examples for this chapter.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset