---
title: fmt_number
output: html
jupyter: python3
---

```{python}
import great_tables as gt
from great_tables import exibble, countrypops
```

Use the exibble dataset to create a gt table. With the `fmt_number()` method, we'll format the num column to have three decimal places (with `decimals=3`) and omit the use of digit separators (with `use_seps=False`).

```{python}
gt.GT(exibble).fmt_number(columns='num', decimals=3).cols_label(char = "character")
```

Use a modified version of the countrypops dataset to create a gt table with row labels. Format all columns to use large-number suffixing (e.g., where `'10,000,000'` becomes `'10M'`) with the `suffixing=True` option.

```{python}
from siuba import *
res = (countrypops
   >> select(_.country_code_3, _.year, _.population)
   >> filter(_.country_code_3.isin(['CHN', 'IND', 'USA', 'PAK', 'IDN']))
   >> filter(_.year > 1975, _.year % 5 == 0)
   >> spread(_.year, _.population)
   >> arrange(-_[2015])
)

# TODO: implement `suffixing`
(gt.GT(res)
   .fmt_integer(columns=1980, scale_by=1/10000)
   .fmt_number(columns=1985)
)

```

In a variation of the previous table, we can combine large-number suffixing with a declaration of the number of significant digits to use. With things like population figures, `n_sigfig=3` is a very good option.

```{python}
# | eval: false
#countrypops |>
#  dplyr::select(country_code_3, year, population) |>
#  dplyr::filter(country_code_3 %in% c('CHN', 'IND', 'USA', 'PAK', 'IDN')) |>
#  dplyr::filter(year > 1975 & year %% 5 == 0) |>
#  tidyr::spread(year, population) |>
#  dplyr::arrange(desc(`2015`)) |>
#  gt(rowname_col='country_code_3') |>
#  fmt_number(suffixing=True, n_sigfig=3)
```

There can be cases where you want to show numbers to a large number of decimal places but also drop the unnecessary trailing zeros for low-precision values. Let's take a portion of the towny dataset and format the latitude and longitude columns with `fmt_number()`. We'll have up to 5 digits displayed as decimal values, but we'll also unconditionally drop any runs of trailing zeros in the decimal part with `drop_trailing_zeros=True`.

```{python}
# | eval: false
towny |>
  dplyr::select(name, latitude, longitude) |>
  dplyr::slice_head(n=10) |>
  gt() |>
  fmt_number(decimals=5, drop_trailing_zeros=True) |>
  # replace -name with [latitude, longitude]
  ## cols_merge(columns=-name, pattern='{1}, {2}') |>
  cols_label(
    name~'Municipality',
    latitude='Location'
  )
```

