TryBugHunt
rustType errorMedium

Price of 19.99 is stored as 1998 cents

BugFind the bug and fix the code

What it should do

price_to_cents(price) converts a price in dollars to a whole number of cents. Example: price_to_cents(19.99) → 1999

What happens instead

price_to_cents(19.99) returns 1998 instead of 1999, and price_to_cents(0.29) returns 28.

fn price_to_cents(price: f64) -> i64 {
    (price * 100.0) as i64
}

Test a custom input to verify an edge case (e.g. empty lists, negative numbers, duplicates).

⏱️0:00
Hints
🏆 0 hints = Flawless Solve
Think & Test Cooldown
2:00 remaining

Take a moment to read the bug symptom and trace the code with Run & Check before unlocking Hint 1.

Hint 2
Unlocks after Hint 1
Hint 3
Unlocks after Hint 2

This bug belongs to the type errors pattern

Integer overflow, truncating casts with as, and types that do not convert the way you expect.

What you'll practise

A medium Rust debugging exercise about type errors: integer overflow, truncating casts with as, and types that do not convert the way you expect.

The checks your fix must pass

Signs of this kind of bug

Spoiler: why this bug happens(try it first; the hints get warmer one at a time)

What went wrong: 19.99 cannot be stored exactly as an f64. The nearest value is a tiny bit less, so 19.99 * 100.0 is 1998.9999999999998. Casting with as i64 does not round. It cuts off everything after the point, giving 1998.

The fix: Round first, then cast: (price * 100.0).round() as i64.

Remember: as from a float to an integer always truncates toward zero. Money calculations with floats are almost never exact, so round before you convert, or keep money as integer cents from the start.

The pattern behind it: type errors.

More type errors to practise

Embed this challenge on your site

Paste this into any web page or blog post. Visitors fix the bug right there, in their browser.

<iframe src="https://trybughunt.com/embed/cc1bf4b5-9c8a-4aa8-99db-fa2d3af86d6a" title="Debugging challenge: Price of 19.99 is stored as 1998 cents" width="100%" height="580" loading="lazy" style="border:1px solid #d4d4d8;border-radius:12px;max-width:760px"></iframe>
<p style="font-size:14px">Debugging challenge from <a href="https://trybughunt.com/challenges/cc1bf4b5-9c8a-4aa8-99db-fa2d3af86d6a">TryBugHunt</a></p>