Willcode4cash icon

NumericExtension class

Willcode4cash | PRO | 09/09/16 05:45:05 PM UTC | 0 ⭐ | 251 👁️ | Never ⏰ | []
C# |

2.05 KB

|

None

|

0 👍

/

0 👎

namespace MyApp.Extensions
{
    using System;
    using System.Globalization;
    using System.Net;
 
    public static class NumberExtensions
    {
        /// <summary>Appends the numeric ordinal.</summary>
        /// <param name="num">The number.</param>
        /// <returns>A string.</returns>
        public static string AppendNumericOrdinal(int num)
        {
            switch (num % 100)
            {
                case 11:
                case 12:
                case 13:
                    return num.ToString(CultureInfo.InvariantCulture) + "th";
            }
 
            switch (num % 10)
            {
                case 1:
                    return num.ToString(CultureInfo.InvariantCulture) + "st";
 
                case 2:
                    return num.ToString(CultureInfo.InvariantCulture) + "nd";
 
                case 3:
                    return num.ToString(CultureInfo.InvariantCulture) + "rd";
 
                default:
                    return num.ToString(CultureInfo.InvariantCulture) + "th";
            }
        }
 
        /// <summary>An extension method that converts an unsigned integer to an IP address.</summary>
        /// <param name="address">The address to act on.</param>
        /// <returns>address as a string.</returns>
        public static string UIntToIPAddress(this uint address)
        {
            return new IPAddress(BitConverter.GetBytes(address)).ToString();
        }
 
        /// <summary>Determines whether the specified number is prime.</summary>
        /// <param name="number">The number.</param>
        /// <returns>true if prime, false if not.</returns>
        public static bool IsPrime(this int number)
        {
            if ((number % 2) == 0)
            {
                return number == 2;
            }
 
            var sqrt = (int)Math.Sqrt(number);
 
            for (var t = 3; t <= sqrt; t = t + 2)
            {
                if (number % t == 0) return false;
            }
 
            return number != 1;
        }
    }
}

Comments