|
| 1 | +--- |
| 2 | +Title: '.Truncate()' |
| 3 | +Description: 'Returns the integer part of a specified number by removing any fractional digits.' |
| 4 | +Subjects: |
| 5 | + - 'Code Foundations' |
| 6 | + - 'Computer Science' |
| 7 | +Tags: |
| 8 | + - 'Methods' |
| 9 | + - 'Numbers' |
| 10 | + - 'Arithmetic' |
| 11 | + - 'Functions' |
| 12 | +CatalogContent: |
| 13 | + - 'learn-c-sharp' |
| 14 | + - 'paths/computer-science' |
| 15 | +--- |
| 16 | + |
| 17 | +The **`Math.Truncate()`** class method returns the integer part of a specified number by removing any fractional digits. |
| 18 | + |
| 19 | +## Syntax |
| 20 | + |
| 21 | +```pseudo |
| 22 | +Math.Truncate(d); |
| 23 | +The Math.Truncate() method takes one parameter, d, which is the number to truncate (this can be a double or decimal). The method returns the integer part of d (of the same type), except if the value of d equals: |
| 24 | +
|
| 25 | +NaN, then it returns NaN. |
| 26 | +
|
| 27 | +NegativeInfinity, then it returns NegativeInfinity. |
| 28 | +
|
| 29 | +PositiveInfinity, then it also returns PositiveInfinity. |
| 30 | +
|
| 31 | +Note: Math.Truncate() always rounds towards zero. This means Truncate(2.8) is 2, and Truncate(-2.8) is -2. This is different from Math.Floor(), which always rounds down (e.g., Math.Floor(-2.8) would be -3). |
| 32 | +
|
| 33 | +Example |
| 34 | +The following example demonstrates the Math.Truncate() method with both a positive and a negative double. It highlights how the method rounds towards zero in both cases. |
| 35 | +
|
| 36 | +using System; |
| 37 | +
|
| 38 | +public class Example { |
| 39 | + public static void Main(string[] args) { |
| 40 | + double positiveValue = 12.9; |
| 41 | + double negativeValue = -4.7; |
| 42 | +
|
| 43 | + Console.WriteLine("Truncating " + positiveValue + " gives: " + Math.Truncate(positiveValue)); |
| 44 | + Console.WriteLine("Truncating " + negativeValue + " gives: " + Math.Truncate(negativeValue)); |
| 45 | + } |
| 46 | +} |
| 47 | +
|
| 48 | +This example results in the following output: |
| 49 | +
|
| 50 | +Truncating 12.9 gives: 12 |
| 51 | +Truncating -4.7 gives: -4 |
| 52 | +
|
| 53 | +Codebyte Example |
| 54 | +The following example is runnable and returns the truncated value of the given number: |
| 55 | +using System; |
| 56 | +
|
| 57 | +public class Example { |
| 58 | + public static void Main(string[] args) { |
| 59 | + // Number to truncate |
| 60 | + double number = 2.71828; |
| 61 | +
|
| 62 | + Console.WriteLine("The truncated value of " + number + " is: " + Math.Truncate(number)); |
| 63 | +
|
| 64 | + // Example with a negative number |
| 65 | + double negativeNumber = -3.14159; |
| 66 | + Console.WriteLine("The truncated value of " + negativeNumber + " is: " + Math.Truncate(negativeNumber)); |
| 67 | + } |
| 68 | +} |
| 69 | +``` |
0 commit comments