Open In App

C# | Math.Truncate() Method

Improve
Improve
Like Article
Like
Save
Share
Report

In C#, Math.Truncate() is a math class method which is used to compute an integral part of a specified decimal number or double-precision floating-point number. This method can be overloaded by passing the different type of parameters to it as follows:

  • Math.Truncate(Decimal)
  • Math.Truncate(Double)

Math.Truncate(Decimal)

This method is used to compute an integral part of a specified decimal number.

Syntax: 

public static decimal Truncate(decimal dec)

Parameter:

dec: It is the specified number which is to be truncated and type of this parameter is System.Decimal.

Return Type: This method only return the integral part of dec and discard the fractional part. The type of this method is System.Decimal.

Example: 

C#




// C# Program to illustrate the
// Math.Truncate(Decimal) Method
using System;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
  
        // variables of Decimal type
        Decimal dec = 45.89511m;
        Decimal dec2 = 54569.478021m;
  
        // using function and displaying result
        Console.WriteLine(Math.Truncate(dec));
        Console.WriteLine(Math.Truncate(dec2));
    }
}


Output: 

45
54569

Math.Truncate(Double)

This method is used to compute an integral part of a specified double precision floating point number.

Syntax: 

public static double Truncate(decimal dob)

Parameter:

dob: It is the specified number which is to be truncated and type of this parameter is System.Double.

Return Type: This method only returns an integral part of dob and discard the fractional part. The type of this method is System.Double.

Note: If dob is NaN, then method will return NaN value and If dob is PositiveInfinity, then method will return PositiveInfinity value. If dob is NegativeInfinity, then method will return NegativeInfinity value.

Example: 

C#




// C# Program to illustrate the
// Math.Truncate(Double) Method
using System;
  
class Geeks {
  
    // Main Method
    public static void Main()
    {
  
        // variables of Double type
        Double dob = 45649.25649800;
        Double dob2 = 2000150.2654459780;
  
        // using function and displaying result
        Console.WriteLine(Math.Truncate(dob));
        Console.WriteLine(Math.Truncate(dob2));
    }
}


Output: 

45649
2000150

There can be other ways to truncate numbers like casting it to an int, but it does not always work. As compare to other Math methods, this is probably the most reliable way to perform the required tasks.
 



Last Updated : 02 Jul, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads