C Truncation Guide: Casting, floor, and Integer Division

目次

1. Introduction | Why Is “Truncation” Important?

In programming, the truncation of numeric values plays a very important role. Especially in low‑level languages like C, you need to be meticulous about data precision and type handling.

Truncation Is “Intentional Error Adjustment”

Truncation is the process of removing the fractional part or remainder of a number, converting it to a simpler form. It is a type of rounding, and by intentionally limiting the calculation results, it can help stabilize program behavior and optimize performance. For example, truncating amounts less than one yen in payment calculations, or handling array indices as integers—such scenarios are common in everyday programming.

In C, There Are Cases Where Truncation Happens Automatically

In C, truncation can occur automatically even if the developer doesn’t intend it. For instance, dividing two int variables results in an integer, so the fractional part is discarded.
int a = 5 / 2;  // Result is 2; the fractional part is truncated
If you don’t understand this behavior correctly, it can lead to calculation errors and unintended bugs.

Common Misunderstandings About Truncation Methods

Even when we say “numeric truncation,” there are various methods and rules.
  • Implicit truncation via integer arithmetic
  • Explicit truncation by casting a floating‑point number to int
  • Truncation using the floor() function from math.h
  • Advanced methods that change the rounding mode
Since each has different operational rules and outcomes, choosing the appropriate method for the intended use is required.

2. Truncation behavior for integers and cautions

In C, operations between integers have characteristics that differ from other high‑level languages. In particular, the “truncation behavior of integer division” is one of the points where beginners often stumble. This section explains the rules of truncation in integer arithmetic with concrete code examples.

Integer division automatically truncates the fractional part

In C, when you divide integer types such as int, the result is also an integer type, and the fractional part is automatically truncated. This process is also called “implicit truncation” and occurs always without any special syntax.
#include <stdio.h>

int main() {
    int a = 5;
    int b = 2;
    int result = a / b;

    printf("%d\n", result);  // Output: 2
    return 0;
}
In this case, the actual calculation result is 2.5, but because it is an integer type, the fractional part is truncated and 2 is output. If you expect 2.5 without noticing this behavior, it will lead to unintended results, so be careful.

Be aware of division behavior with negative numbers

Another point to watch is division with “negative numbers”. In C, the C99 and later standards explicitly define rounding toward zero as the specification.
#include <stdio.h>

int main() {
    int a = -5;
    int b = 2;
    int result = a / b;

    printf("%d\n", result);  // Output: -2
    return 0;
}
In this code, the result of -5 ÷ 2 is -2.5, but truncation yields -2. Note that the behavior is rounding toward zero (‑2) rather than rounding down (‑3).

Differences across compilers or C versions?

In pre‑C99 environments or some older compilers, the behavior of division with negative numbers was implementation‑dependent. However, today most environments conform to C99, and “rounding toward zero” is standardized. Still, when writing code that runs on multiple platforms, it is advisable to be mindful of rounding direction differences.

How to intentionally obtain a fractional result

When you need the fractional part in integer division, explicitly cast the types.
double result = (double)a / b;  // 5 → 5.0, result: 2.5
年収訴求

3. Truncating Floating-Point Numbers | How to Use the floor Function and Its Features

In C, if you want to truncate the fractional part, the typical method that can be used on floating-point numbers (float and double) is the floor() function. This section provides a detailed explanation of the basic usage and behavior of floor(), and the differences from other similar functions.

What is the floor function? Basic usage

floor() function is a function that truncates the fractional part of the specified number and returns the nearest “smaller” integer. This is also referred to as rounding toward the negative direction.

Including math.h is required

#include <stdio.h>
#include <math.h>

int main() {
    double val = 3.7;
    double result = floor(val);

    printf("%.1f
", result);  // Output: 3.0
    return 0;
}
In this example, 3.7 is truncated to 3.0.

Be aware of behavior with negative numbers

The biggest characteristic of the floor() function is that it always rounds toward the smaller (negative) direction. This is clearly different from a cast that truncates toward zero ((int)).
#include <stdio.h>
#include <math.h>

int main() {
    double val = -3.7;
    double result = floor(val);

    printf("%.1f
", result);  // Output: -4.0
    return 0;
}
In this case, -3.7 is truncated to -4.0. Instead of rounding toward zero, floor rounds to the smaller integer.

Differences from ceil and round

C also provides other “rounding” functions besides floor(). Let’s compare their differences.
FunctionBehaviorExample (-3.7)
floor()Truncate toward smaller integer (negative direction)-4.0
ceil()Round up toward larger integer (positive direction)-3.0
round()Round to the nearest integer-4.0
Since each serves a different purpose, it’s important to choose the function based on how you want to round.

When should you use the floor function?

floor() is suitable, for example, when displaying a price after discount by truncating it or when you need to manage loop termination with an integer, and generally in situations where clear control is prioritized over precision.
double price = 1234.56;
double discounted = floor(price * 100) / 100;  // Truncate discounted price
Thus, it is effective in scenarios where you want to perform calculations that intentionally avoid giving the user an overly favorable result.

4. How Casting Truncates and the Differences

C language allows you to truncate the fractional part by converting a floating‑point number to an integer type via a type cast. This is a very simple method, but it behaves differently from the floor() function, so it is important to understand the differences correctly.

Truncation by Casting from Floating‑Point to Integer Types

Casting‑based truncation is a method of explicitly changing a variable’s type. For example, converting a double value to an int automatically discards the fractional part.
#include <stdio.h>

int main() {
    double val = 3.7;
    int result = (int)val;

    printf("%d\n", result);  // Output: 3
    return 0;
}
In this example, the fractional part of 3.7 is truncated, resulting in 3. Because casting rounds toward zero, both positive and negative numbers are rounded in the direction of zero.

Differences in Behavior for Negative Values

The biggest difference between casting and the floor() function is the result when handling negative numbers.
#include <stdio.h>
#include <math.h>

int main() {
    double val = -3.7;
    int cast_result = (int)val;
    double floor_result = floor(val);

    printf("Cast: %d\n", cast_result);     // Output: -3
    printf("floor: %.1f\n", floor_result);     // Output: -4.0

    return 0;
}
As this code shows:
  • Cast: -3.7-3 (toward zero)
  • floor: -3.7-4.0 (toward negative infinity)
If you use casting without knowing this difference, unexpected rounding errors can occur, causing the logic to break.

Advantages and Caveats of Using Casts

Advantages:

  • Implementation is simple and does not depend on standard library functions, so it runs fast.
  • No need to include math.h.

Caveats:

  • Be aware that the rounding direction is always toward zero.
  • When handling negative values, the result may differ from the intended one.
  • Casting also serves as a means of indicating explicit intent, so it is advisable to add appropriate comments in contexts where readability is important.

Choosing the Right Approach Based on Use Case

When asked “Which should be used?”, you can decide as follows.
Purpose of the operationMethod to use
Always round down (to the smaller value), including negative numbersfloor() function
Truncate toward zero (performance‑focused)Cast (int)
Mathematically nearest integerround() function
In this way, by choosing the appropriate method for the purpose, you can write robust, bug‑free code.

5. Changing Rounding Mode Using fenv.h (Advanced)

In C, when you want to control the rounding method of floating‑point operations within a program, you can use the standard library fenv.h. By using this library, you can change the global rounding mode (Rounding Mode). This is especially useful in fields where the accuracy and reproducibility of numerical calculations are important (scientific computing, financial systems, etc.).

What Is a Rounding Mode?

A rounding mode is the method that decides how to approximate when a floating‑point operation’s result cannot be represented as an integer. C supports the following four rounding modes.
Constant NameDescription
FE_TONEARESTRound to the nearest value (round half up)
FE_DOWNWARDRound toward negative infinity (same as floor)
FE_UPWARDRound toward positive infinity (same as ceil)
FE_TOWARDZERORound toward zero (same as truncation)

How to Set the Rounding Mode

By using fenv.h, you can explicitly set and retrieve the current rounding mode.

Example of Setting the Rounding Mode (fesetround())

#include <stdio.h>
#include <math.h>
#include <fenv.h>
#pragma STDC FENV_ACCESS ON

int main() {
    fesetround(FE_DOWNWARD);  // Set rounding mode to "downward" (toward negative infinity)

    double x = 3.7;
    double result = rint(x);  // rint function rounds according to the current rounding mode

    printf("Result: %.1f\n", result);  // Output: 3.0
    return 0;
}
rint() is a function that rounds a number according to the currently set rounding mode. >How to Retrieve the Rounding Mode (fegetround()) If you want to check the current rounding mode, write it as follows.
int mode = fegetround();

if (mode == FE_DOWNWARD) {
    printf("Current rounding mode is FE_DOWNWARD.\n");
}
This allows you to dynamically determine which rounding rule is applied.

Notes and Usage Constraints

  • #pragma STDC FENV_ACCESS ON is a directive that tells the compiler to interpret the rounding mode correctly; if you omit it, fesetround() may not work properly.
  • Support for fenv.h may be incomplete in some older compilers or environments.
  • Rounding modes can be shared across threads, so caution is required in multithreaded environments.

When Should You Use fenv.h?

fenv.h is useful in the following situations:
  • Scientific computing and statistical processing, where rounding errors can affect results
  • When you want to standardize the floating‑point rounding method
  • When you need to fix rounding behavior during testing or verification
On the other hand, for everyday application development, the usual floor() or cast is often sufficient, so the use of fenv.h is limited.

6. Practical Example: Truncation Techniques in Monetary and Array Processing

So far we’ve learned the basics of truncation in C, but how is it actually used in real-world development? In this section, we explain how truncation is used in the two common practical scenarios, two frequently encountered situations, “monetary calculations” and “array or loop processing”.

Monetary Processing: Truncate Fractions to Accurately Compute Billing Amounts

For example, when calculating the pre‑tax price from a tax‑included price or displaying a discounted amount, you may truncate fractions less than 1 yen.

Example: Truncating amounts less than 1 yen (using floor)

#include <stdio.h>
#include <math.h>

int main() {
    double price = 1234.56;
    double discounted = price * 0.9;  // 10% discount
    double rounded = floor(discounted);  // truncate fractional part

    printf("Before discount: %.2f\n", price);
    printf("After discount (truncated): %.0f yen\n", rounded);  // Output: 1111 yen
    return 0;
}
By using floor(), you can make the displayed amount easy for users to understand and adjust it to the intended value.

Array Processing: Truncation in Index Calculation

When handling arrays or splitting data, truncating to an integer is essential. For example, when you want to divide the total number of data evenly, you need to truncate the fractional part and convert it to an index.

Example: Divide 10 items into 3 parts and determine each range

#include <stdio.h>

int main() {
    int total = 10;
    int parts = 3;
    int chunk_size = total / parts;  // truncation via integer division

    printf("Number of items per group (truncated): %d\n", chunk_size);  // Output: 3
    return 0;
}
In this case, 10 ÷ 3 = 3.333..., but because the division is between int types, it is automatically truncated to 3.

Practical Applications: Can Also Be Used for Integer Conversion of Coordinates and Fractions

  • When drawing graphs, calculate how many pixels between each tick mark.
  • Treat an entered “percentage (%)” as an integer weight.
  • When converting time in seconds to “minutes + seconds”, truncate the fractional part and convert to an integer.
Even in such situations, deliberate truncation plays an important role.

Things to Watch Out for When Using Truncation

  1. Accidentally using rounding up or rounding to nearest
  • Clearly distinguish the use of “floor” and casting
  1. Order of calculations involving fractional parts
  • The basic approach is to compute first and truncate later; getting the order wrong can easily cause calculation errors
  1. Be aware of floating-point errors in monetary processing
  • If necessary, convert to integers (e.g., yen to sen as int) for processing

7. Common Mistakes: Points Where Beginners Stumble and How to Fix Them

In C, truncation may seem like a simple feature at first glance, but there are many pitfalls that beginners easily make. Here we introduce the patterns that are especially prone to stumbling and how to address them.

When you want a decimal from integer division but keep it as int

One of the most common mistakes is this. Even though you expect to get a fractional part when dividing two integers, the result becomes an integer.

Example: Unexpected Output

int a = 5;
int b = 2;
double result = a / b;  // → result is 2.0 (fractional part lost)
Because integer arithmetic is performed at the point of a / b, the fractional part is lost.

Solution: Explicitly cast one operand

double result = (double)a / b;  // → result is 2.5
The remedy is to cast at least one operand to double or float before the operation.

Truncating negative numbers can yield unintended results

When truncating negative values, if you don’t understand the difference in behavior between casting and floor(), unexpected rounding occurs.

Example: Difference between cast and floor

double val = -3.7;

int cast_result = (int)val;      // → -3 (toward zero)
double floor_result = floor(val); // → -4.0 (toward negative)

Solution:

  • If you want to round “always down” (to the smaller value), use floor()
  • If you want to round “toward zero”, use a cast
You need to choose based on your purpose.

Forgetting to include math.h causes a build error

When using functions such as floor() or ceil(), if you forget #include <math.h>, a compilation error occurs. Also, on Windows you need to add the linker option -lm (on Linux, gcc -lm is required).

Solution:

  • Always write #include <math.h>
  • Add the -lm option when building (only where needed)

Incorrect order of truncation leads to unintended results

If you truncate in the middle of a calculation, the overall result can become offset.

Example: Mistake in discount calculation

double price = 1000.0;
double discount = floor(price) * 0.9;  // This is OK
double incorrect = floor(price * 0.9);  // You might actually want to use this

Solution:

  • First clarify what you want to truncate, then decide the order
  • Adding comments to explain the intent helps prevent bugs

Be aware of floating-point errors

Floating-point arithmetic has values that cannot be represented exactly in binary, which can lead to unexpected errors.

Example: Comparison fails even though values look identical

double a = 0.1 * 3;
if (a == 0.3) {
    // May behave as expected
}

Solution:

  • Use an epsilon (tolerance) for comparisons
  • For monetary values or precise integer processing, replace with integer types (e.g., manage 1 yen as 100 cents using int) is also effective

8. FAQ | Common Questions About Truncation in C

In this section, we have compiled the points that readers often wonder about when dealing with “truncation” in C, in a Q&A format. We assume situations that are commonly encountered in work and learning environments and provide clear answers.

Q1: What happens when you cast a float or double to an int?

A1: The fractional part is discarded, and the value is rounded toward zero.
double val = 3.9;
int result = (int)val;  // → 3
Because casting always results in round toward zero, both positive and negative numbers are rounded toward zero.

Q2: Can the floor() function be used with negative numbers?

A2: Yes, it can. floor() always rounds down (toward the negative direction).
double val = -2.3;
double result = floor(val);  // → -3.0
Note that it does not round toward zero. Since the result differs from casting, choosing the appropriate function based on the purpose is important.

Q3: Why does the fractional part disappear when dividing integers?

A3: In C, division of integers yields an integer result, and the fractional part is automatically discarded.
int a = 5;
int b = 2;
double result = a / b;  // → 2.0
Thus, because the integer operation is performed first and then converted to floating point, you do not get the expected result.

Solution:

double result = (double)a / b;  // → 2.5

Q4: How can you truncate the result of floating-point division?

A4: You can use the floor() function to truncate floating-point numbers.
double val = 5.8;
double result = floor(val);  // → 5.0
In some cases, you may choose to use a cast (int), but be aware of the difference in rounding direction.

Q5: What is rounding mode? When should it be used?

A5: Rounding mode is a feature that specifies the direction of rounding during floating-point operations. By using fenv.h and setting options like FE_DOWNWARD or FE_TOWARDZERO, you can control the behavior of functions such as rint(). However, it is not commonly used in typical development. It is often used in scientific, engineering, or financial programs that require precise numeric control.

Q6: What is the difference between the round() and floor() functions?

A6: round() rounds to the nearest integer, while floor() always truncates down to the smaller integer.
Function3.7-3.7
round()4.0-4.0
floor()3.0-4.0
Since the behavior differs for positive and negative values, choose based on your purpose.

Q7: Is the order of truncation operations important?

A7: Yes, it is very important. The order of calculations can significantly affect the final result.
double price = floor(1234.56 * 0.9);  // truncate after discount
// vs
double discounted = floor(1234.56) * 0.9;  // truncate before discount

Solution:

  • Clearly define what you want to truncate before deciding the order
  • Adding comments to explain the intent of the processing helps prevent bugs

9. Summary | Use the appropriate truncation method according to the purpose

C language’s “truncation” operations are not merely mathematical actions; they are programming techniques that should be chosen carefully based on the processing content and context. Through this article we have introduced various truncation methods and the differences in their characteristics and uses. Here, let’s recap how to choose the optimal truncation method according to the purpose.

Main truncation methods and guidelines for choosing among them

MethodOverviewFeaturesSuitable Use Cases
int castfloating-point → integertruncates toward zerosimple rounding, performance‑focused
floor() functiontruncates floating-point toward negative directionalways to the smaller integerfinancial calculations, control‑logic
integer divisionautomatically discards the fractional partno explicit handling needed, but requires cautionarray partitioning, counting operations, etc.
fenv.h rounding controlallows setting rounding mode for precise controlsuits scientific/technical calculations and special needsprecision‑critical numeric processing, rounding behavior verification

Things to keep in mind for accurate results

  1. Pay attention to rounding direction differences floor() rounds toward negative, cast rounds toward zero. Since their behavior differs, choose according to the purpose.
  2. Clarify the order of operations Whether you compute while still in floating-point and then truncate, or truncate first and then operate can significantly affect the result.
  3. Always be aware of type and operation combinations Operations between ints, casting to double, float precision. If you proceed without regard to types, unintended results can occur.

Finally

Truncation in programming is often dismissed as “just the fractional part,” but a single choice can determine whether bugs appear and affect user experience. Because of its nature, C is a language that requires developers to explicitly express their intent. Therefore, handling truncation correctly is a crucial skill for building reliable programs. We hope this guide deepens your understanding of “C truncation” and helps you write more precise code.