Skip to content

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_idamount_centsfee_cents
1199959
225030
312345null

Expected output

payment_idamountfee
119.990.6
22.50.3
3123.45null

Hints

Hint 1{% macro cents_to_dollars(column_name, scale=2) %} ... {% endmacro %}. The body is the SQL text the call is replaced with.
Hint 2Inside, {{ column_name }} prints the column name you were given and {{ scale }} the number: round({{ column_name }} / 100, {{ scale }}).
Hint 3Use /, not //: in DuckDB // is integer division and drops the cents before rounding.

More dbt problems

All dbt problems