C++ Standard Library C++ STL Library

C# Math - Truncate() Function



The C# Truncate() method is used to round the given number towards zero. It returns the nearest integral value with absolute value less than the argument. In special cases it returns the following:

  • If the argument is NaN, the method returns NaN.
  • If the argument is positive infinity or negative infinity, the method returns same as the argument.

Syntax

public static decimal Truncate (decimal x);

Parameters

x Specify a number.

Return Value

Returns the nearest integral value with absolute value less than the argument.

Example:

In the example below, Truncate() function returns the nearest integral value with absolute value less than the argument.

using System;

class MyProgram {
  static void Main(string[] args) {
    Console.WriteLine("Math.Truncate(2.5) = "
                      + Math.Truncate(2.5));
    Console.WriteLine("Math.Truncate(5.78) = "
                      + Math.Truncate(5.78));
    Console.WriteLine("Math.Truncate(-3.5) = "
                      + Math.Truncate(-3.5));
    Console.WriteLine("Math.Truncate(-10.33) = "
                      + Math.Truncate(-10.33));
    Console.WriteLine("Math.Truncate(Double.NaN) = "
                      + Math.Truncate(Double.NaN));
    Console.WriteLine("Math.Truncate(Double.NegativeInfinity) = "
                      + Math.Truncate(Double.NegativeInfinity));
    Console.WriteLine("Math.Truncate(Double.PositiveInfinity) = "
                      + Math.Truncate(Double.PositiveInfinity));                      
  }
}

The output of the above code will be:

Math.Truncate(2.5) = 2
Math.Truncate(5.78) = 5
Math.Truncate(-3.5) = -3
Math.Truncate(-10.33) = -10
Math.Truncate(Double.NaN) = NaN
Math.Truncate(Double.NegativeInfinity) = -Infinity
Math.Truncate(Double.PositiveInfinity) = Infinity

❮ C# Math Methods