How can I force division to be floating point? Division keeps rounding down to 0?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
When dividing two integers, many programming languages perform integer division by default, discarding the fractional part. 1 / 3 evaluates to 0 in C, C++, Java, and Python 2 because both operands are integers. The fix is to ensure at least one operand is a float: cast explicitly ((float)a / b), use a float literal (1.0 / 3), or use the language's true-division operator. The exact approach depends on the language.
Python
Python 3 always performs true division with /, returning a float:
Python 2 performed integer division by default with /:
C / C++
In C, (double)a / b promotes b to double before the division. This is called implicit type promotion.
Java
JavaScript
JavaScript always uses floating-point division — there is no integer division:
C#
Go
Ruby
Ruby's / between two integers returns an integer:
Rust
Common Pitfalls
- Casting the result instead of the operand:
(double)(a / b)performs integer division first (getting0), then casts0to0.0. You must cast before the division:(double)a / b. - Assuming
/always returns a float: In Python 3 and JavaScript it does, but in C, Java, Go, Rust, and Ruby,/between two integers returns an integer. Know your language's default. - Losing precision with
floatvsdouble: Afloat(32-bit) has about 7 significant digits. Adouble(64-bit) has about 15. For calculations requiring precision, always usedouble(ordecimalin C# for financial math). - Negative number rounding direction: Integer division truncates toward zero in C, Java, and Go (
-7 / 2 = -3), but floors toward negative infinity in Python (-7 // 2 = -4). This difference causes bugs when porting code between languages. - Division by zero behavior: Integer division by zero throws an exception or is undefined behavior. Float division by zero returns
InfinityorNaNin most languages. Neither is the correct answer — always check for zero denominators.
Summary
- Integer division discards the fractional part in most compiled languages
- Cast at least one operand to float/double before dividing:
(double)a / b - Python 3 and JavaScript always return floats from
/— no casting needed - Use
//in Python orMath.floor()in JavaScript for explicit integer division - Cast the operand, not the result:
(double)(a / b)still performs integer division first - Use
double(notfloat) for precision, anddecimalfor financial calculations

