C Basic
C Math Functions
C trunc() Function
Photo Credit to CodeToFun
đ Introduction
In C programming, the trunc()
function is a part of the <math.h> library, and it is used for truncating a floating-point number to its integral part.
Truncation involves removing the fractional part of the number, leaving only the integer part.
In this tutorial, we'll explore the usage and functionality of the trunc()
function in C.
đĄ Syntax
The syntax for the trunc()
function is as follows:
double trunc(double x);
- x: The floating-point number to be truncated.
đ Example
Let's dive into an example to illustrate how the trunc()
function works.
#include <stdio.h>
#include <math.h>
int main() {
double originalNumber = 3.75;
// Use the trunc() function
double truncatedNumber = trunc(originalNumber);
// Output the result
printf("Original number: %.2f\n", originalNumber);
printf("Truncated number: %.2f\n", truncatedNumber);
return 0;
}
đģ Output
Original number: 3.75 Truncated number: 3.00
đ§ How the Program Works
In this example, the trunc()
function is used to truncate the floating-point number 3.75, and the result is printed.
âŠī¸ Return Value
The trunc()
function returns the truncated value of the input x. It returns a double value.
đ Common Use Cases
The trunc()
function is useful when you need to discard the decimal part of a floating-point number and retain only the integer part. This can be beneficial in scenarios where you want to perform integer-based operations or display the integral part of a number.
đ Notes
- The
trunc()
function rounds towards zero. It effectively removes everything after the decimal point without rounding to the nearest integer. - If the argument is already an integer or is NaN, the result is the same as the argument.
đĸ Optimization
The trunc()
function is a relatively efficient operation, and optimization is typically not a primary concern. However, ensure that you use it appropriately based on your specific requirements.
đ Conclusion
The trunc()
function in C provides a straightforward way to truncate the fractional part of a floating-point number. It is a valuable tool for scenarios where integer-based operations or displaying the integral part of a number is essential.
Feel free to experiment with different floating-point numbers and observe the behavior of the trunc()
function. Happy coding!
đ¨âđģ Join our Community:
Author
For over eight years, I worked as a full-stack web developer. Now, I have chosen my profession as a full-time blogger at codetofun.com.
Buy me a coffee to make codetofun.com free for everyone.
Buy me a Coffee
If you have any doubts regarding this article (C trunc() Function) please comment here. I will help you immediately.