Functions, Dates and Cleaning · Problem 18 of 118

Cents to Dollars

EasyFunctions, Dates and CleaningBank data

Balances are stored as whole cents. For accounts 1 to 6, return account_id and balance in currency units with the cents (for example 1924.0 for 192400), sorted by account_id.

Hint 1

In SQL, dividing two integers gives an integer: 7 / 2 is 3.

Hint 2

Divide by 100.0 (a decimal) instead of 100.

Reference solution

SELECT account_id,
       balance_cents / 100.0 AS balance
FROM accounts
WHERE account_id BETWEEN 1 AND 6
ORDER BY account_id;

When both operands are integers, SQLite (and most databases) performs integer division and drops the remainder: 52078 / 100 is 520, not 520.78. Make one side a decimal (100.0, or CAST(... AS REAL)) to get a decimal result. This is one of the most frequent silent bugs in SQL reports: the query runs, the numbers look plausible, and they are wrong.

Another way. Convert one side to a decimal type first.

SELECT account_id,
       CAST(balance_cents AS REAL) / 100 AS balance
FROM accounts
WHERE account_id BETWEEN 1 AND 6
ORDER BY account_id;