Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Math.Truncate() Method in C#
The Math.Truncate() method in C# is used to remove the fractional part of a number and return only the integral part. It works with both decimal and double data types, effectively cutting off all digits after the decimal point without rounding.
Syntax
The Math.Truncate() method has two overloads −
public static decimal Truncate(decimal d) public static double Truncate(double d)
Parameters
- d − A decimal or double number to truncate.
Return Value
Returns the integral part of the specified number. The return type matches the input parameter type (decimal returns decimal, double returns double).
Using Math.Truncate() with Decimal Values
Example
using System;
public class Demo {
public static void Main() {
decimal val1 = 25.46467m;
decimal val2 = 45.9989m;
decimal val3 = 678.325m;
decimal val4 = -12.789m;
Console.WriteLine("Original: " + val1 + " -> Truncated: " + Math.Truncate(val1));
Console.WriteLine("Original: " + val2 + " -> Truncated: " + Math.Truncate(val2));
Console.WriteLine("Original: " + val3 + " -> Truncated: " + Math.Truncate(val3));
Console.WriteLine("Original: " + val4 + " -> Truncated: " + Math.Truncate(val4));
}
}
The output of the above code is −
Original: 25.46467 -> Truncated: 25 Original: 45.9989 -> Truncated: 45 Original: 678.325 -> Truncated: 678 Original: -12.789 -> Truncated: -12
Using Math.Truncate() with Double Values
Example
using System;
public class Demo {
public static void Main() {
double val1 = 95.86467;
double val2 = 25.11;
double val3 = 878.325;
double val4 = -56.999;
Console.WriteLine("Original: " + val1 + " -> Truncated: " + Math.Truncate(val1));
Console.WriteLine("Original: " + val2 + " -> Truncated: " + Math.Truncate(val2));
Console.WriteLine("Original: " + val3 + " -> Truncated: " + Math.Truncate(val3));
Console.WriteLine("Original: " + val4 + " -> Truncated: " + Math.Truncate(val4));
}
}
The output of the above code is −
Original: 95.86467 -> Truncated: 95 Original: 25.11 -> Truncated: 25 Original: 878.325 -> Truncated: 878 Original: -56.999 -> Truncated: -56
Comparison with Other Methods
| Method | Input: 25.7 | Input: -25.7 | Behavior |
|---|---|---|---|
Math.Truncate() |
25 | -25 | Removes fractional part |
Math.Floor() |
25 | -26 | Rounds down to nearest integer |
Math.Ceiling() |
26 | -25 | Rounds up to nearest integer |
Math.Round() |
26 | -26 | Rounds to nearest integer |
Conclusion
The Math.Truncate() method simply removes the fractional part of a number without performing any rounding. Unlike Math.Floor() or Math.Ceiling(), it always moves toward zero, making it useful when you need the integral part regardless of the number's sign.
