Advertisement
Willcode4cash

NumericExtension class

Sep 9th, 2016
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.05 KB | None | 0 0
  1. namespace MyApp.Extensions
  2. {
  3.     using System;
  4.     using System.Globalization;
  5.     using System.Net;
  6.  
  7.     public static class NumberExtensions
  8.     {
  9.         /// <summary>Appends the numeric ordinal.</summary>
  10.         /// <param name="num">The number.</param>
  11.         /// <returns>A string.</returns>
  12.         public static string AppendNumericOrdinal(int num)
  13.         {
  14.             switch (num % 100)
  15.             {
  16.                 case 11:
  17.                 case 12:
  18.                 case 13:
  19.                     return num.ToString(CultureInfo.InvariantCulture) + "th";
  20.             }
  21.  
  22.             switch (num % 10)
  23.             {
  24.                 case 1:
  25.                     return num.ToString(CultureInfo.InvariantCulture) + "st";
  26.  
  27.                 case 2:
  28.                     return num.ToString(CultureInfo.InvariantCulture) + "nd";
  29.  
  30.                 case 3:
  31.                     return num.ToString(CultureInfo.InvariantCulture) + "rd";
  32.  
  33.                 default:
  34.                     return num.ToString(CultureInfo.InvariantCulture) + "th";
  35.             }
  36.         }
  37.  
  38.         /// <summary>An extension method that converts an unsigned integer to an IP address.</summary>
  39.         /// <param name="address">The address to act on.</param>
  40.         /// <returns>address as a string.</returns>
  41.         public static string UIntToIPAddress(this uint address)
  42.         {
  43.             return new IPAddress(BitConverter.GetBytes(address)).ToString();
  44.         }
  45.  
  46.         /// <summary>Determines whether the specified number is prime.</summary>
  47.         /// <param name="number">The number.</param>
  48.         /// <returns>true if prime, false if not.</returns>
  49.         public static bool IsPrime(this int number)
  50.         {
  51.             if ((number % 2) == 0)
  52.             {
  53.                 return number == 2;
  54.             }
  55.  
  56.             var sqrt = (int)Math.Sqrt(number);
  57.  
  58.             for (var t = 3; t <= sqrt; t = t + 2)
  59.             {
  60.                 if (number % t == 0) return false;
  61.             }
  62.  
  63.             return number != 1;
  64.         }
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement