Math.Truncate
This C# method eliminates numbers after the decimal. It acts upon a decimal or floating-point number, calculating the integral part of a number.
Math.Truncate
is reliable and easy to use. Its functionality differs from Math.Round
. Sometimes casting to int
can truncate a number effectively as well.
This program calls the Math.Truncate
method on a decimal and double
. The Math.Truncate
overloads called in this program are implemented differently in .NET.
double
2.913 was truncated to 2.Math.Round
for this functionality.using System; class Program { static void Main() { decimal a = 1.223M; double b = 2.913; // Truncate the decimal and double, receiving new numbers. decimal result1 = Math.Truncate(a); double result2 = Math.Truncate(b); // Print the results. Console.WriteLine(result1); Console.WriteLine(result2); } }1 2
There are some other ways you can truncate numbers. If you have a double
value and cast it to an int
, you can erase all the values past the decimal place.
// These two statements sometimes provide the same result. b = Math.Truncate(b); b = (double)(int)b;
We explored the Math.Truncate
method. This method erases all the numbers past the decimal place in a double
or decimal number type.