What is Math.Truncate() in C#?

C# has a built-in Math class that provides useful mathematical functions and operations. The class has the Truncate() function, which is used to compute the integral part of a specified number by discarding the fractional part.

Truncating by removing the fractional part

Syntax

public static decimal Truncate (decimal value);

OR

public static double Truncate (double value);

Parameters

  • Value: This is of Decimal type in case of Decimal Variant, Double type in case of Double Variant, and represents the input value for which we have to truncate.

Return value

  • Decimal: This returns a Decimal number after removing the fractional part of the value.

    OR

  • Double: This returns a Double number after removing the fractional part of the value.

  • NaN / PositiveInfinity / NegativeInfinity: This returns NaN, PositiveInfinity and NegativeInfinity respectively for the respective input values.

Truncate() rounds value to the nearest integer towards zero.

Example

using System;
class Educative
{
static void Main()
{
double value = 32.274;
double result = Math.Truncate(value);
System.Console.WriteLine("Truncate Double(32.274) = "+ result);
decimal value2 = 34.812m;
decimal result2 = Math.Truncate(value2);
System.Console.WriteLine("Truncate Decimal(34.812m) = "+ result2);
double result3 = Math.Truncate(Double.NaN);
System.Console.WriteLine("Truncate(NaN) = "+ result3);
}
}

Free Resources