🔢

Module 5 Video - fprintf: Decimal Places

Mar 7, 2025

Controlling Decimal Places in MATLAB

Introduction

  • Default behavior of MATLAB when using %f as an insertion point is to display six decimal places.
  • Decimal precision can be customized easily.

Customizing Decimal Precision

Specifying Decimal Places

  • Syntax: Use %.nf where n is the number of decimal places desired.
    • Example: %.2f results in two decimal places.
  • Usage: To display a value with specific precision:
    • Example: 7.00 is displayed as 7.00 by specifying %.2f.

Integer Display

  • When integer display is preferable (e.g., whole number counts):
    • Example: 7 instead of 7.00 by using %.0f.

Numeric Formats: General (%g)

  • %g Format: MATLAB chooses the best format automatically.
    • Displays integers as integers.
    • Uses scientific notation for very large/small numbers.

Working with Variables

  • Example: Define mon_mass = 369.85;
  • Usage in print statements:
    • Example: "The monster's mass is %.1f kilograms" results in "369.9", demonstrating rounding (not truncation).

Formatting Control

Minimum Number of Print Locations

  • Syntax: %n.mf where n is the minimum number of print locations.
  • Usage:
    • Example: %3.1f and %5.1f provide the same result if the number requires fewer places.
    • %9.1f ensures at least nine spaces are used.
  • Purpose: Align numbers in a column for better readability across multiple lines.

Left Justification

  • Syntax: %-n.mf uses a negative sign to left-justify.
    • Spaces appear to the right instead of the left.

Summary

  • Understanding and controlling print format ensures values are displayed consistently.
  • Useful for aligning data in tables or repeated outputs.

Next Steps

  • Further exploration of fprintf functionality in subsequent presentations.