C# .Truncate()
The Math.Truncate() method in C# returns the integer part of a specified number by removing any fractional digits. It works with both decimal and double types.
Syntax
Math.Truncate(double d)
Or, alternatively:
Math.Truncate(decimal d)
Parameters:
d(double|decimal): The number whose fractional part is to be discarded.
Return value:
- Returns a
doubleif adoubleis passed and adecimalif adecimalis passed. - Special values like
NaN,PositiveInfinity, andNegativeInfinityare returned as-is.
Note:
Math.Truncate()always rounds towards zero. This meansMath.Truncate(2.8)is 2, andMath.Truncate(-2.8)is -2. This is different fromMath.Floor(), which always rounds down (e.g.,Math.Floor(-2.8)would be -3).
Example 1: Using double
In this example, a double value is truncated to its integer part:
using System;public class Example {public static void Main() {double positiveValue = 12.9;double negativeValue = -4.7;Console.WriteLine("Truncating " + positiveValue + " gives: " + Math.Truncate(positiveValue));Console.WriteLine("Truncating " + negativeValue + " gives: " + Math.Truncate(negativeValue));}}
This example results in the following output:
Truncating 12.9 gives: 12Truncating -4.7 gives: -4
Example 2: Using decimal
In this example, a decimal value is truncated without using the m suffix by explicitly casting a double to decimal:
using System;public class Example {public static void Main() {decimal decValue = (decimal)45.678;decimal negDecValue = (decimal)-23.456;Console.WriteLine("Truncating decimal " + decValue + " gives: " + Math.Truncate(decValue));Console.WriteLine("Truncating decimal " + negDecValue + " gives: " + Math.Truncate(negDecValue));}}
The output of this code is:
Truncating decimal 45.678 gives: 45Truncating decimal -23.456 gives: -23
Codebyte Example
In this example, both double and decimal values are truncated in a small array of numbers:
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C# on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn Microsoft's popular C# programming language, used to make websites, mobile apps, video games, VR, and more.
- Beginner Friendly.15 hours