Skip to main content

More Formatting Options

The Formatting Values page introduced the basics of fmt_number(), fmt_currency(), fmt_date(), and fmt_time(). But Great Tables has a much larger formatting toolkit. This page covers additional formatters that handle percentages, fractions, byte sizes, date-times, durations, scientific units, chemical formulas, icons, flags, images, boolean values, Markdown, and more. Each formatter transforms raw cell data into presentation-ready content.

When choosing a formatter, start with the semantic meaning of your data. If a column represents a file size, reach for fmt_bytes() rather than fmt_number() with manual suffix logic. If a column holds time durations, use fmt_duration() instead of formatting seconds by hand. Semantic formatters produce more consistent output and handle edge cases (like unit boundaries and scaling) automatically, so you get correct results without writing extra logic.

Percentage Formatting

The fmt_percent() method formats numeric values as percentages. By default, it assumes the input values are proportions (e.g., 0.25 becomes "25.00%"). If your values are already in percent form, set scale_values=False.

import polars as pl
from great_tables import GT

pct_df = pl.DataFrame({
    "metric": ["Conversion rate", "Bounce rate", "Click-through"],
    "proportion": [0.034, 0.621, 0.158],
    "already_pct": [3.4, 62.1, 15.8],
})

(
    GT(pct_df, rowname_col="metric")
    .fmt_percent(columns="proportion", decimals=1)
    .fmt_percent(columns="already_pct", decimals=1, scale_values=False)
)
proportion already_pct
Conversion rate 3.4% 3.4%
Bounce rate 62.1% 62.1%
Click-through 15.8% 15.8%

Both columns display correctly as percentages, but the proportion column needed scaling (the default behavior) while already_pct did not.

Fraction Formatting

The fmt_fraction() method shows decimal values as mixed fractions. This suits quantities that are conventionally given as fractions, like recipe amounts or measurements in inches.

fraction_df = pl.DataFrame({
    "ingredient": ["Flour", "Sugar", "Butter", "Vanilla"],
    "cups": [2.25, 0.75, 0.5, 0.0625],
})

(
    GT(fraction_df, rowname_col="ingredient")
    .fmt_fraction(columns="cups", accuracy=16)
)
cups
Flour 2 1/4
Sugar 3/4
Butter 1/2
Vanilla 1/16

The accuracy= argument sets the largest allowed denominator (here 16). It can also be one of the keywords "low" (the default, for denominators up to 9), "med" (up to 99), or "high" (up to 999). Set layout="diagonal" to typeset the fractions with a diagonal bar instead of a slash.

Byte Size Formatting

The fmt_bytes() method converts raw byte counts into human-readable sizes. It automatically selects the appropriate unit (kB, MB, GB, etc.) based on the magnitude of the value.

bytes_df = pl.DataFrame({
    "file": ["photo.jpg", "video.mp4", "document.pdf", "database.sqlite"],
    "size_bytes": [2_048_000, 1_573_000_000, 524_288, 85_000_000_000],
})

(
    GT(bytes_df, rowname_col="file")
    .fmt_bytes(columns="size_bytes", standard="decimal")
)
size_bytes
photo.jpg 2 MB
video.mp4 1.6 GB
document.pdf 524.3 kB
database.sqlite 85 GB

The standard= argument controls the unit system. Use "decimal" for powers of 1000 (kB, MB, GB) or "binary" for powers of 1024 (KiB, MiB, GiB).

(
    GT(bytes_df, rowname_col="file")
    .fmt_bytes(columns="size_bytes", standard="binary")
)
size_bytes
photo.jpg 2 MiB
video.mp4 1.5 GiB
document.pdf 512 KiB
database.sqlite 79.2 GiB

With the binary standard, the same byte values display in KiB, MiB, and GiB units. Choose whichever standard matches the conventions of your domain.

As a rule of thumb, use decimal units (kB, MB, GB) for storage marketed to consumers (disk drives, cloud storage quotas, and network transfer speeds all use powers of 1000). Use binary units (KiB, MiB, GiB) for memory and technical contexts where powers of 1024 are precise, such as RAM capacity, cache sizes, and buffer allocations. Picking the right standard avoids confusing your readers with numbers that don’t match what they see elsewhere.

Date-Time Formatting

The fmt_date() and fmt_time() methods covered earlier each handle half of a timestamp. For values holding both a date and a time, fmt_datetime() takes a date_style= and a time_style= together and joins the two parts with sep=.

from datetime import datetime

datetime_df = pl.DataFrame({
    "event": ["Doors open", "Keynote", "Reception"],
    "starts": [
        datetime(2024, 9, 16, 8, 30),
        datetime(2024, 9, 16, 9, 15),
        datetime(2024, 9, 17, 18, 0),
    ],
})

(
    GT(datetime_df, rowname_col="event")
    .fmt_datetime(columns="starts", date_style="wd_m_day_year", time_style="h_m_p")
)
starts
Doors open Mon, Sep 16, 2024 8:30 AM
Keynote Mon, Sep 16, 2024 9:15 AM
Reception Tue, Sep 17, 2024 6:00 PM

The style keywords are the same ones used by fmt_date() and fmt_time(), so a table that mixes date, time, and date-time columns can present them consistently.

Duration Formatting

The fmt_duration() method formats numeric values (or timedelta objects) as styled time duration strings. You specify the input unit and the method handles the conversion and display.

duration_df = pl.DataFrame({
    "event": ["Sprint", "Marathon", "Triathlon", "Ultra"],
    "seconds": [58, 7_380, 21_900, 187_265],
})

(
    GT(duration_df, rowname_col="event")
    .fmt_duration(columns="seconds", input_units="seconds")
)
seconds
Sprint 58s
Marathon 2h 3m
Triathlon 6h 5m
Ultra 2d 4h 1m 5s

The duration_style= argument controls the output format. The available styles are:

  • "narrow" (the default): compact format like "2d 3h 15m"
  • "wide": spelled out like "2 days 3 hours 15 minutes"
  • "colon-sep": clock format like "2/03:15:00"
  • "iso": ISO 8601 format like "P2DT3H15M"
(
    GT(duration_df, rowname_col="event")
    .fmt_duration(columns="seconds", input_units="seconds", duration_style="wide")
)
seconds
Sprint 58 seconds
Marathon 2 hours 3 minutes
Triathlon 6 hours 5 minutes
Ultra 2 days 4 hours 1 minute 5 seconds

You can limit the number of output units with max_output_units= to keep the display concise.

(
    GT(duration_df, rowname_col="event")
    .fmt_duration(columns="seconds", input_units="seconds", max_output_units=2)
)
seconds
Sprint 58s
Marathon 2h 3m
Triathlon 6h 5m
Ultra 2d 4h

Limiting the output to two units (e.g., "2d 4h" instead of "2d 4h 1m 5s") keeps the display compact when exact precision is not required.

Engineering Notation

The fmt_engineering() method formats values in engineering notation, where the exponent is always a multiple of 3. This aligns with SI prefixes (kilo, mega, milli, micro, etc.) and is common in technical and scientific contexts.

eng_df = pl.DataFrame({
    "quantity": ["Resistance", "Capacitance", "Frequency", "Power"],
    "value": [4700.0, 0.0000001, 2400000000.0, 0.0035],
})

(
    GT(eng_df, rowname_col="quantity")
    .fmt_engineering(columns="value")
)
value
Resistance 4.70 × 103
Capacitance 100.00 × 10−9
Frequency 2.40 × 109
Power 3.50 × 10−3

Each value is expressed with a mantissa between 1 and 999 and an exponent that is a multiple of 3. This makes it straightforward to mentally convert to SI prefixes (e.g., 4.70 × 103 is 4.7 kilo).

Engineering notation is preferred over scientific notation when your audience thinks in terms of SI prefixes. Because the exponent is always a multiple of 3, values map directly to familiar units: kilohms, microfarads, gigahertz, milliwatts, and so on. Readers can interpret the numbers without mental conversion. If your data spans a wide range of magnitudes in a technical domain, engineering notation is almost always the better choice.

To go one step further and write the SI prefix itself, use fmt_number_si(). It picks the prefix from the size of each value and can append a unit with unit=.

power_df = pl.DataFrame({
    "device": ["Sensor", "Laptop", "Power plant"],
    "power": [0.0035, 65.0, 2_400_000_000.0],
})

(
    GT(power_df, rowname_col="device")
    .fmt_number_si(columns="power", unit="W")
)
power
Sensor 3.50 mW
Laptop 65.00 W
Power plant 2.40 GW

Parts-Per Formatting

The fmt_partsper() method formats values as parts-per quantities: per mille, ppm, ppb, and more. By default, it assumes input values are proportions and scales them accordingly.

ppm_df = pl.DataFrame({
    "substance": ["Lead", "Mercury", "Arsenic"],
    "concentration": [0.000015, 0.000001, 0.00001],
})

(
    GT(ppm_df, rowname_col="substance")
    .fmt_partsper(columns="concentration", to_units="ppm")
)
concentration
Lead 15.00 ppm
Mercury 1.00 ppm
Arsenic 10.00 ppm

The to_units= argument accepts the following values: "per-mille", "per-myriad", "pcm", "ppm", "ppb", "ppt", and "ppq".

Roman Numeral Formatting

The fmt_roman() method converts integer values into Roman numerals. This can be useful for numbering chapters, sections, or ranked items.

roman_df = pl.DataFrame({
    "event": ["Opening", "Keynote", "Workshop", "Closing"],
    "order": [1, 2, 3, 4],
})

(
    GT(roman_df, rowname_col="event")
    .fmt_roman(columns="order")
)
order
Opening I
Keynote II
Workshop III
Closing IV

The case= argument accepts "upper" (the default, producing "I", "II", "III") or "lower" (producing "i", "ii", "iii").

A close relative is fmt_index(), which turns integers into letters (1 becomes "A", 2 becomes "B", and so on), with the same case= argument. This is handy for labeling items in outlines or multiple-choice options.

(
    GT(roman_df, rowname_col="event")
    .fmt_index(columns="order", case="lower")
)
order
Opening a
Keynote b
Workshop c
Closing d

Scientific Units

The fmt_units() method renders measurement units with proper subscripts, superscripts, and special symbols. It uses a concise notation syntax where ^ indicates superscripts, _ indicates subscripts, and special names are referenced with colons.

units_df = pl.DataFrame({
    "quantity": ["Speed of light", "Boltzmann constant", "Planck constant", "Acceleration"],
    "units": ["m/s", "J K^-1", "kg m^2 s^-1", "m s^-2"],
})

(
    GT(units_df, rowname_col="quantity")
    .fmt_units(columns="units")
)
units
Speed of light m/s
Boltzmann constant J K−1
Planck constant kg m2 s−1
Acceleration m s−2

The units notation supports Greek letters (:alpha:, :beta:, :sigma:), chemical formulas in percent delimiters (%H2O%), and combined subscripts and superscripts (t_i^2).

Chemical Formulas

For columns that hold chemical formulas or reactions, fmt_chem() sets the subscripts, charges, and reaction arrows. Element counts become subscripts, and charges (a terminating + or -, or a numbered charge like ^2-) become superscripts.

chem_df = pl.DataFrame({
    "name": ["Water", "Sulfate ion", "Hydroxide ion", "Photosynthesis"],
    "formula": ["H2O", "SO4^2-", "OH-", "6 CO2 + 6 H2O -> C6H12O6 + 6 O2"],
})

(
    GT(chem_df, rowname_col="name")
    .fmt_chem(columns="formula")
)
formula
Water H2O
Sulfate ion SO42−
Hydroxide ion OH−
Photosynthesis 6 CO2 + 6 H2O → C6H12O6 + 6 O2

True/False Formatting

The fmt_tf() method transforms boolean values into visual indicators. It offers a variety of preset styles including text labels, check marks, shapes, and arrows.

tf_df = pl.DataFrame({
    "feature": ["Dark mode", "Auto-save", "Spell check", "Notifications"],
    "enabled": [True, True, False, True],
    "premium": [False, True, False, True],
})

(
    GT(tf_df, rowname_col="feature")
    .fmt_tf(columns="enabled", tf_style="check-mark")
    .fmt_tf(columns="premium", tf_style="circles")
)
enabled premium
Dark mode ✔ ⭘
Auto-save ✔ ●
Spell check ✘ ⭘
Notifications ✔ ●

The available tf_style= values include: "true-false", "yes-no", "up-down", "check-mark", "circles", "squares", "diamonds", "arrows", "triangles", and "triangles-lr".

You can also apply colors to the True/False indicators using the colors= argument.

(
    GT(tf_df, rowname_col="feature")
    .fmt_tf(columns="enabled", tf_style="check-mark", colors=["green", "red"])
)
enabled premium
Dark mode ✔ False
Auto-save ✔ True
Spell check ✘ False
Notifications ✔ True

When you provide two colors, the first applies to True values and the second to False values.

Markdown in Cells

The fmt_markdown() method renders Markdown-formatted text that appears in cells. This is useful when your data contains text with emphasis, links, or other inline formatting.

md_df = pl.DataFrame({
    "package": ["polars", "pandas", "numpy"],
    "description": [
        "**Fast** DataFrame library for *Rust* and Python",
        "Flexible data analysis with **labeled** axes",
        "Fundamental package for *scientific computing*",
    ],
})

(
    GT(md_df, rowname_col="package")
    .fmt_markdown(columns="description")
)
description
polars Fast DataFrame library for Rust and Python
pandas Flexible data analysis with labeled axes
numpy Fundamental package for scientific computing

The Markdown is converted to HTML during rendering, so standard inline Markdown syntax (bold, italic, links, code) is supported.

Icons in Cells

The fmt_icon() method renders Font Awesome icons based on icon names stored in cells. This is a visually engaging way to represent categories, statuses, or types.

icon_df = pl.DataFrame({
    "platform": ["Web", "Mobile", "Desktop"],
    "icon_name": ["globe", "mobile", "desktop"],
    "users": [45000, 32000, 12000],
})

(
    GT(icon_df, rowname_col="platform")
    .fmt_icon(columns="icon_name", fill_color="steelblue")
    .fmt_number(columns="users", compact=True)
)
icon_name users
Web 45.00K
Mobile 32.00K
Desktop 12.00K

The fill_color= argument accepts a single color (applied to all icons) or a dictionary mapping icon names to specific colors.

(
    GT(icon_df, rowname_col="platform")
    .fmt_icon(
        columns="icon_name",
        fill_color={"globe": "royalblue", "mobile": "forestgreen", "desktop": "slategray"}
    )
)
icon_name users
Web 45000
Mobile 32000
Desktop 12000

Using a dictionary for fill_color= lets you assign semantically meaningful colors to each icon, making the visual distinction immediate.

Country Flags

The fmt_flag() method generates flag icons from ISO 3166-1 country codes (two- or three-letter codes). This is useful for international datasets.

country_df = pl.DataFrame({
    "country_code": ["US", "GB", "JP", "DE", "BR"],
    "country": ["United States", "United Kingdom", "Japan", "Germany", "Brazil"],
    "gdp_trillion": [25.5, 3.1, 4.2, 4.1, 1.9],
})

(
    GT(country_df, rowname_col="country")
    .fmt_flag(columns="country_code")
    .fmt_number(columns="gdp_trillion", decimals=1)
    .cols_label(country_code="Flag", gdp_trillion="GDP (USD trillions)")
)
Flag GDP (USD trillions)
United States United States 25.5
United Kingdom United Kingdom 3.1
Japan Japan 4.2
Germany Germany 4.1
Brazil Brazil 1.9

The flags render as small inline images with a hover tooltip showing the country name (controlled by use_title=).

Images in Cells

The fmt_image() method renders image paths or URLs as inline images within cells. This is useful for product catalogs, team rosters, or any dataset where visual identification matters.

img_df = pl.DataFrame({
    "planet": ["Earth", "Mars", "Jupiter"],
    "image_file": ["earth.png", "mars.png", "jupiter.png"],
    "diameter_km": [12742, 6779, 139820],
})

(
    GT(img_df, rowname_col="planet")
    .fmt_image(columns="image_file", path="images/", height="40px")
    .fmt_number(columns="diameter_km", decimals=0)
)

The path= argument provides a common prefix for all file references, and height=/width= control the rendered dimensions. When encode=True (the default), local image files are base64-encoded directly into the HTML output, making the table self-contained.

Aligning on the Decimal Mark

Formatting with a fixed number of decimal places lines up the decimal marks in a column. When values have varying numbers of decimal places (e.g., after drop_trailing_zeros=True), the cols_align_decimal() method pads the formatted values with figure spaces so that the decimal marks still line up.

measure_df = pl.DataFrame({
    "sample": ["A", "B", "C", "D"],
    "reading": [1.5, 10.25, 100.0, 0.125],
})

(
    GT(measure_df, rowname_col="sample")
    .fmt_number(columns="reading", decimals=3, drop_trailing_zeros=True)
    .cols_align_decimal(columns="reading")
)
reading
A   1.5  
B  10.25 
C 100    
D   0.125

Because the alignment happens after formatting, it works with the output of any of the fmt_*() methods, including values with a % or other suffix.

Custom Formatting with fmt()

When none of the built-in formatters fit your needs, the generic fmt() method lets you supply any function as a formatter. The function receives a raw cell value and should return a formatted string.

def format_score(value):
    """Convert a 0-100 score to a letter grade."""
    if value >= 90:
        return "A"
    elif value >= 80:
        return "B"
    elif value >= 70:
        return "C"
    elif value >= 60:
        return "D"
    else:
        return "F"

grades_df = pl.DataFrame({
    "student": ["Alice", "Bob", "Charlie", "Diana"],
    "score": [95, 82, 67, 91],
})

(
    GT(grades_df, rowname_col="student")
    .fmt(fns=format_score, columns="score")
)
score
Alice A
Bob B
Charlie D
Diana A

The fmt() method is the escape hatch for any formatting logic that the specialized fmt_*() methods do not cover. Your function can return plain text or HTML strings for rich formatting.

fmt() is what makes Great Tables’ formatting system fully extensible. Any transformation you can express in Python (lookups, conditional logic, external API calls) can become a cell formatter. If you find yourself writing the same custom formatter repeatedly, consider wrapping it in a reusable function and sharing it across tables. This is exactly the pattern described in the Extending Great Tables page.

The formatting methods in Great Tables cover a wide spectrum of data types and presentation needs. From scientific notation to country flags, from boolean indicators to custom functions, you have the tools to make every column in your table look exactly right for its audience and context.