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.
Syntax
public static decimal Truncate (decimal value);
OR
public static double Truncate (double value);
Parameters
- Value: This is of
Decimaltype in case of Decimal Variant,Doubletype in case of Double Variant, and represents the input value for which we have to truncate.
Return value
-
Decimal: This returns a
Decimalnumber after removing the fractional part of thevalue.OR
-
Double: This returns a
Doublenumber after removing the fractional part of thevalue. -
NaN / PositiveInfinity / NegativeInfinity: This returns
NaN,PositiveInfinityandNegativeInfinityrespectively for the respective input values.
Truncate()roundsvalueto 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);}}