8. Write a cents_to_dollars Macro
Difficulty: Easy · Topic: Macros
Every model in the project converts cents to currency units by hand, each slightly differently. Write the macro cents_to_dollars(column_name, scale=2) in macros/cents_to_dollars.sql: it returns the SQL expression that divides the column by 100 and rounds the result to scale decimal places.
The model that calls it is fixed (you only write the macro):
select
payment_id,
{{ cents_to_dollars('amount_cents') }} as amount,
{{ cents_to_dollars('fee_cents', 1) }} as fee
from {{ ref('stg_payments_raw') }}
Hidden tests call it in other ways too, such as scale=0 by keyword. A null column stays null.
Your model is compiled like dbt does and run in DuckDB against 3 test cases, including hidden edge cases.
Sample inputs
{{ ref('stg_payments_raw') }}
| payment_id | amount_cents | fee_cents |
|---|---|---|
| 1 | 1999 | 59 |
| 2 | 250 | 30 |
| 3 | 12345 | null |
Expected output
| payment_id | amount | fee |
|---|---|---|
| 1 | 19.99 | 0.6 |
| 2 | 2.5 | 0.3 |
| 3 | 123.45 | null |
Hints
Hint 1
{% macro cents_to_dollars(column_name, scale=2) %} ... {% endmacro %}. The body is the SQL text the call is replaced with.Hint 2
Inside,{{ column_name }} prints the column name you were given and {{ scale }} the number: round({{ column_name }} / 100, {{ scale }}).Hint 3
Use/, not //: in DuckDB // is integer division and drops the cents before rounding.