C# Math.Truncate Calculates Integral Part

This C# tutorial demonstrates the Math.Truncate method from the System namespace.

Math.Truncate eliminates numbers after the decimal.

It acts upon a decimal or floating-point number. It calculate the integral part of a number. Math.Truncate is reliable and easy-to-use. Its functionality differs from Math.Round.

 

 

Example. This program declares and assigns a decimal and double type and then calls the Math.Truncate method on each variable. The Math.Truncate overloads called in this program are implemented differently in the .NET Framework.

DecimalOverload

 

C# program that uses Math.Truncate method

using System;

class Program
{
    static void Main()
    {
	decimal a = 1.223M;
	double b = 2.913;

	a = Math.Truncate(a);
	b = Math.Truncate(b);

	Console.WriteLine(a);
	Console.WriteLine(b);
    }
}

Output

1
2

You can see that the decimal 1.223 was truncated to 1, and the double 2.913 was truncated to 2. Please notice that the value 2.9 is not rounded up to 3. You would want Math.Round for this functionality.

Math.Round

 

Discussion. 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. This is an optimization, but it does not always work.

Cast, Int

 

However: This version would fail in certain cases such as with large doubles. In other cases it would be faster.

Double

Example statements: C#

// These two statements sometimes provide the same result.
b = Math.Truncate(b);
b = (double)(int)b;

 

Summary. We explored the Math.Truncate method. This method erases all the numbers past the decimal place in a double or decimal number type. As with other Math methods, this is probably the most reliable way to perform the required task.