Programming Fundamentals · Interview question

Why is if (x == 0.1f) unreliable, and what should you write instead?

A strong answer

Most decimal fractions, including 0.1, can't be represented exactly in binary floating point. The constant 0.1f rounds to the nearest representable float, which is slightly off from one-tenth. Any computation that should mathematically produce 0.1f will rarely produce that exact bit pattern, so == returns false even when you'd expect true. The right approach is to compare with a tolerance: if (fabsf(x - 0.1f) < 1e-6f). This says "x is close enough to 0.1 to count as equal," which is what you almost always actually mean. For exact decimals (money, counters) use integers, e.g. store cents, not dollars, and compare with == again.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Conditionals

How a program makes decisions. if, else if, and else, with the dangling-else trap and the ternary shortcut for one-line choices.

More Conditionals questions

Browse all 472 interview questions