Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
truncate
math
communitycreator

What is Math.Truncate() in C#?

Arslan Bajwa

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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);
Decimal Variant

OR

public static double Truncate (double value);
Double Variant

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);

    }
}

RELATED TAGS

c#
truncate
math
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring