|
1 | 1 | ---
|
2 |
| -Title: '.Abs()' |
3 |
| -Description: 'Computes the non-negative value of a number regardless of its sign.' |
| 2 | +Title: 'Abs()' |
| 3 | +Description: 'Returns the absolute value of a specified number.' |
4 | 4 | Subjects:
|
5 |
| - - 'Code Foundations' |
6 | 5 | - 'Computer Science'
|
| 6 | + - 'Web Development' |
7 | 7 | Tags:
|
| 8 | + - 'Functions' |
| 9 | + - 'Math' |
8 | 10 | - 'Methods'
|
9 | 11 | - 'Numbers'
|
10 |
| - - 'Arithmetic' |
11 |
| - - 'Functions' |
12 | 12 | CatalogContent:
|
13 | 13 | - 'learn-c-sharp'
|
14 | 14 | - 'paths/computer-science'
|
15 | 15 | ---
|
16 | 16 |
|
17 |
| -The **`Math.Abs()`** class method returns the absolute value of a given number. |
| 17 | +The C# **`Math.Abs()`** method is a static method that returns the absolute value of a specified number. The absolute value of a number is its distance from zero on the number line, always expressed as a positive value or zero. |
18 | 18 |
|
19 |
| -## Syntax |
| 19 | +## Syntax of C# `Math.Abs()` |
20 | 20 |
|
21 | 21 | ```pseudo
|
22 | 22 | Math.Abs(number);
|
23 | 23 | ```
|
24 | 24 |
|
25 |
| -The `Math.Abs()` method takes only one parameter, `number`, a `decimal`, `double` or `integer` type number. The method returns the absolute value of the `number` with the same type as the `number`, except if the value of `number` equals: |
| 25 | +**Parameters:** |
| 26 | + |
| 27 | +- `number`: The numeric value for which to calculate the absolute value. This can be of type `decimal`, `double`, `float`, `int`, `long`, `sbyte`, `short`, or `IntPtr`. |
| 28 | + |
| 29 | +**Return value:** |
26 | 30 |
|
27 |
| -- `NaN` (not a number), then it returns `NaN` |
28 |
| -- `NegativeInfinity`, then it returns `PositiveInfinity` |
29 |
| -- `PositiveInfinity`, then it also returns `PositiveInfinity` |
| 31 | +Returns the absolute value of the specified number with the same data type as the input parameter. Special cases include: |
30 | 32 |
|
31 |
| -## Example |
| 33 | +- If the input is `NaN` (Not a Number), returns `NaN` |
| 34 | +- If the input is negative infinity, returns positive infinity |
| 35 | +- If the input is positive infinity, returns positive infinity |
32 | 36 |
|
33 |
| -The following example uses the `Math.Abs()` method to return the absolute value of a `decimal` and a `double` type number. Then, the `Console.WriteLine()` function prints the results to the console: |
| 37 | +## Example 1: Basic Usage of C# `Math.Abs()` |
| 38 | + |
| 39 | +This example demonstrates the fundamental use of the `Math.Abs()` method with different numeric types to show how it returns the non-negative equivalent of the number: |
34 | 40 |
|
35 | 41 | ```cs
|
36 | 42 | using System;
|
37 | 43 |
|
38 |
| -public class Example { |
39 |
| - public static void Main() { |
40 |
| - decimal num1 = -1.23M; |
41 |
| - double num2 = 6.674E-11; |
| 44 | +public class BasicAbsExample |
| 45 | +{ |
| 46 | + public static void Main() |
| 47 | + { |
| 48 | + // Integer examples |
| 49 | + int negativeInt = -42; |
| 50 | + int positiveInt = 15; |
| 51 | + |
| 52 | + // Decimal examples |
| 53 | + decimal negativeDecimal = -3.14m; |
| 54 | + decimal positiveDecimal = 2.71m; |
| 55 | + |
| 56 | + // Calculate absolute values |
| 57 | + int absInt1 = Math.Abs(negativeInt); |
| 58 | + int absInt2 = Math.Abs(positiveInt); |
| 59 | + decimal absDecimal1 = Math.Abs(negativeDecimal); |
| 60 | + decimal absDecimal2 = Math.Abs(positiveDecimal); |
| 61 | + |
| 62 | + // Display results |
| 63 | + Console.WriteLine($"Math.Abs({negativeInt}) = {absInt1}"); |
| 64 | + Console.WriteLine($"Math.Abs({positiveInt}) = {absInt2}"); |
| 65 | + Console.WriteLine($"Math.Abs({negativeDecimal}) = {absDecimal1}"); |
| 66 | + Console.WriteLine($"Math.Abs({positiveDecimal}) = {absDecimal2}"); |
| 67 | + } |
| 68 | +} |
| 69 | +``` |
| 70 | + |
| 71 | +The output of this code is as follows: |
| 72 | + |
| 73 | +```shell |
| 74 | +Math.Abs(-42) = 42 |
| 75 | +Math.Abs(15) = 15 |
| 76 | +Math.Abs(-3.14) = 3.14 |
| 77 | +Math.Abs(2.71) = 2.71 |
| 78 | +``` |
| 79 | + |
| 80 | +## Example 2: Calculating Temperature Difference using `Math.Abs()` |
| 81 | + |
| 82 | +This example shows how `Math.Abs()` can be used in a real-world scenario to calculate the temperature difference between two values, which is always expressed as a positive number: |
42 | 83 |
|
43 |
| - decimal abs1 = Math.Abs(num1); |
44 |
| - double abs2 = Math.Abs(num2); |
| 84 | +```cs |
| 85 | +using System; |
45 | 86 |
|
46 |
| - Console.WriteLine("The absolute value of " + num1 + " is: " + abs1); |
47 |
| - Console.WriteLine("The absolute value of " + num2 + " is: " + abs2); |
| 87 | +public class TemperatureDifference |
| 88 | +{ |
| 89 | + public static void Main() |
| 90 | + { |
| 91 | + // Temperature readings in Celsius |
| 92 | + double morningTemp = -5.2; |
| 93 | + double afternoonTemp = 18.7; |
| 94 | + double eveningTemp = 12.3; |
| 95 | + |
| 96 | + // Calculate temperature differences |
| 97 | + double morningAfternoonDiff = Math.Abs(afternoonTemp - morningTemp); |
| 98 | + double afternoonEveningDiff = Math.Abs(eveningTemp - afternoonTemp); |
| 99 | + double morningEveningDiff = Math.Abs(eveningTemp - morningTemp); |
| 100 | + |
| 101 | + // Display results |
| 102 | + Console.WriteLine("Temperature Analysis:"); |
| 103 | + Console.WriteLine($"Morning: {morningTemp}C"); |
| 104 | + Console.WriteLine($"Afternoon: {afternoonTemp}C"); |
| 105 | + Console.WriteLine($"Evening: {eveningTemp}C"); |
| 106 | + Console.WriteLine(); |
| 107 | + Console.WriteLine("Temperature Differences:"); |
| 108 | + Console.WriteLine($"Morning to Afternoon: {morningAfternoonDiff}C"); |
| 109 | + Console.WriteLine($"Afternoon to Evening: {afternoonEveningDiff}C"); |
| 110 | + Console.WriteLine($"Morning to Evening: {morningEveningDiff}C"); |
48 | 111 | }
|
49 | 112 | }
|
50 | 113 | ```
|
51 | 114 |
|
52 |
| -The example will result in the following output: |
| 115 | +The output of this code is as follows: |
53 | 116 |
|
54 | 117 | ```shell
|
55 |
| -The absolute value of -1.23 is: 1.23 |
56 |
| -The absolute value of 6.674E-11 is: 6.674E-11 |
| 118 | +Temperature Analysis: |
| 119 | +Morning: -5.2°C |
| 120 | +Afternoon: 18.7°C |
| 121 | +Evening: 12.3°C |
| 122 | + |
| 123 | +Temperature Differences: |
| 124 | +Morning to Afternoon: 23.9°C |
| 125 | +Afternoon to Evening: 6.4°C |
| 126 | +Morning to Evening: 17.5°C |
57 | 127 | ```
|
58 | 128 |
|
59 |
| -## Codebyte Example |
| 129 | +## Codebyte Example: Financial Loss Calculator Using `Math.Abs()` |
60 | 130 |
|
61 |
| -The following example is runnable and returns the absolute value of a `double` type number: |
| 131 | +This example demonstrates using `Math.Abs()` in financial applications to calculate the magnitude of profit or loss, regardless of whether the value is positive or negative: |
62 | 132 |
|
63 | 133 | ```codebyte/csharp
|
64 | 134 | using System;
|
65 | 135 |
|
66 |
| -public class Example { |
| 136 | +public class FinancialLossCalculator |
| 137 | +{ |
| 138 | + public static void Main() |
| 139 | + { |
| 140 | + // Investment performance data |
| 141 | + decimal[] monthlyReturns = { 150.75m, -89.50m, 245.30m, -175.25m, 95.60m }; |
| 142 | + string[] months = { "January", "February", "March", "April", "May" }; |
| 143 | +
|
| 144 | + decimal totalAbsoluteChange = 0; |
| 145 | +
|
| 146 | + Console.WriteLine("Monthly Investment Performance:"); |
| 147 | + Console.WriteLine("Month\t\tReturn\t\tAbsolute Change"); |
| 148 | + Console.WriteLine("-----------------------------------------------"); |
67 | 149 |
|
68 |
| - public static void Main() { |
69 |
| - double number = 299792458; |
| 150 | + for (int i = 0; i < monthlyReturns.Length; i++) |
| 151 | + { |
| 152 | + decimal absoluteChange = Math.Abs(monthlyReturns[i]); |
| 153 | + totalAbsoluteChange += absoluteChange; |
70 | 154 |
|
71 |
| - Console.WriteLine("The absolute value of " + number + " is: " + Math.Abs(number)); |
| 155 | + string returnType = monthlyReturns[i] >= 0 ? "Profit" : "Loss"; |
| 156 | + Console.WriteLine($"{months[i]}\t\t${monthlyReturns[i]:F2}\t\t${absoluteChange:F2} ({returnType})"); |
| 157 | + } |
| 158 | +
|
| 159 | + Console.WriteLine("-----------------------------------------------"); |
| 160 | + Console.WriteLine($"Total Absolute Change: ${totalAbsoluteChange:F2}"); |
| 161 | + Console.WriteLine($"Average Absolute Change: ${totalAbsoluteChange / monthlyReturns.Length:F2}"); |
72 | 162 | }
|
73 | 163 | }
|
74 | 164 | ```
|
| 165 | + |
| 166 | +## Frequently Asked Questions |
| 167 | + |
| 168 | +### 1. What happens if I pass a positive number to `Math.Abs()`? |
| 169 | + |
| 170 | +The method returns the same positive number unchanged. For example, `Math.Abs(5)` returns 5. |
| 171 | + |
| 172 | +### 2. Can `Math.Abs()` handle floating-point numbers? |
| 173 | + |
| 174 | +Yes, `Math.Abs()` supports all numeric types including `float`, `double`, and `decimal`. It preserves the data type of the input. |
| 175 | + |
| 176 | +### 3. What does `Math.Abs()` return for zero? |
| 177 | + |
| 178 | +`Math.Abs(0)` returns 0, as the absolute value of zero is zero. |
| 179 | + |
| 180 | +### 4. Can `Math.Abs()` cause overflow exceptions? |
| 181 | + |
| 182 | +Yes, with certain integer types like `Int32.MinValue`, calling `Math.Abs()` can throw an `OverflowException` because the absolute value exceeds the maximum positive value for that type. |
0 commit comments