Csharp/C Sharp/Data Types/Number

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Converting a Number in Another Base to Base10

using System;
using System.Data;

class Class1{
        static void Main(string[] args){
      string base2 = "111";
      string base8 = "117";
      string base10 = "1110";
      string base16 = "11F1FF";
      Console.WriteLine("Convert.ToInt32(base2, 2) = " + 
        Convert.ToInt32(base2, 2));
      Console.WriteLine("Convert.ToInt32(base8, 8) = " + 
        Convert.ToInt32(base8, 8));
      Console.WriteLine("Convert.ToInt32(base10, 10) = " + 
        Convert.ToInt32(base10, 10));
      Console.WriteLine("Convert.ToInt32(base16, 16) = " + 
        Convert.ToInt32(base16, 16));
        }
}


Converting Celsius to Fahrenheit

using System;
using System.Data;
using System.Text.RegularExpressions;
class Class1{
        static void Main(string[] args){
            Console.WriteLine(CtoF(0));      
            Console.WriteLine(CtoF(40));      
            Console.WriteLine(CtoF(50));      
            Console.WriteLine(CtoF(-50));
        }
    public static double CtoF(double celsius)
    {
      return (((0.9/0.5) * celsius) + 32);
    }
}


Converting Degrees to Radians

using System;
using System.Data;

class Class1{
        static void Main(string[] args){
            Console.WriteLine(ConvertDegreesToRadians (180));
            Console.WriteLine(ConvertDegreesToRadians (90));
            Console.WriteLine(ConvertDegreesToRadians (30));
        }
    public static double ConvertDegreesToRadians (double degrees)
    {
      double radians = (Math.PI / 180) * degrees;
      return (radians);
    }  
}


Converting Fahrenheit to Celsius

using System;
using System.Data;
using System.Text.RegularExpressions;
class Class1{
        static void Main(string[] args){
            Console.WriteLine(FtoC(0));      
            Console.WriteLine(FtoC(40));      
            Console.WriteLine(FtoC(50));      
            Console.WriteLine(FtoC(-50));
        }
    public static double FtoC(double fahrenheit)
    {
      return ((0.5/0.9) * (fahrenheit - 32));
    }
}


Converting Radians to Degrees

using System;
using System.Data;

class Class1{
        static void Main(string[] args){
            Console.WriteLine(ConvertRadiansToDegrees (2));
            Console.WriteLine(ConvertRadiansToDegrees (3.1415));
            Console.WriteLine(ConvertRadiansToDegrees (0));
        }
    public static double ConvertRadiansToDegrees(double radians)
    {
      double degrees = (180 / Math.PI) * radians;
      return (degrees);
    }
}


Declare int and use it

//Example3_6.cs, Page 78
using System;
public class Example3_6q {
   public static void Main(string[] args) {
      int number1 = 12;
      int number2 = 23;
      Console.WriteLine("The answer is " + number1 + number2);
      Console.WriteLine("The answer is " + (number1 + number2));
      
   }
}


Determining if a String is a Valid Number by Parse functions

using System;
using System.Data;

class Class1{
        static void Main(string[] args){
      string IsNotNum = "111west";
      string IsNum = "  +111  ";
      string IsFloat = "  23.11  ";
      string IsExp = "  +23 e+11  ";
      
      Console.WriteLine(int.Parse(IsNum));    
        Console.WriteLine(float.Parse(IsNum));    // 111
      Console.WriteLine(float.Parse(IsFloat));  // 23.11
      //Console.WriteLine(float.Parse(IsExp));  // throws
      
      try
      {
        Console.WriteLine(int.Parse(IsNotNum));
      }
      catch (FormatException e)
      {
        Console.WriteLine("Not a numeric value: {0}", e.ToString());  // throws
      }
        }
}


Faster way to get number from string

using System;
using System.Data;
using System.Text.RegularExpressions;
class Class1{
        static void Main(string[] args){
      string IsNotNum = "111west";
      string IsNum = "  +111  ";
      string IsFloat = "  23.11  ";
      string IsExp = "  +23 e+11  ";
      
      Console.WriteLine(GetNumberFromStrFaster(IsNum));    // +111
      Console.WriteLine(GetNumberFromStrFaster(IsNotNum));  // 
      Console.WriteLine(GetNumberFromStrFaster(IsFloat));    // 23.11
      Console.WriteLine(GetNumberFromStrFaster(IsExp));    // 
        }
    public static string GetNumberFromStrFaster(string str)
    {
      str = str.Trim();
      Match m = new Regex(@"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$", RegexOptions.rupiled).Match(str);
      return (m.Value);
    }
}


Is it a double number

using System;
using System.Data;
using System.Text.RegularExpressions;
class Class1{
        static void Main(string[] args){
      string IsNotNum = "111west";
      string IsNum = "  +111  ";
      string IsFloat = "  23.11  ";
      string IsExp = "  +23 e+11  ";
      
      Console.WriteLine(IsNumericFromTryParse(IsNum));    // True
      Console.WriteLine(IsNumericFromTryParse(IsNotNum));    // False
      Console.WriteLine(IsNumericFromTryParse(IsFloat));    // True
      Console.WriteLine(IsNumericFromTryParse(IsExp));    // False
        }
    public static bool IsNumericFromTryParse(string str)
    {
      double result = 0;
      return (double.TryParse(str, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.CurrentInfo, out result));
    }
}


Numeric Parsing Demo

using System;
public class NumericParsing
{
    public static void Main()
    {
        int value = Int32.Parse("99953");
        double dval = Double.Parse("1.3433E+35");
        Console.WriteLine("{0}", value);
        Console.WriteLine("{0}", dval);
    }
}


shows that using an instance of the System.Int32 stucture is the same as using the int keyword

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa
Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
//
//  TestInt.cs -- shows that using an instance of the System.Int32 stucture
//  is the same as using the int keyword.
//
//                Compile this program with the following command line:
//                    C:>csc TestInt.cs
//
namespace nsTestInt
{
    using System;
    
    public class TestInt
    {
        static public void Main ()
        {
           System.Int32 x;
           OutInt (out x);
           Console.WriteLine ("The integer is " + x);
           x = 42;
           ShowInt (x);
           ChangeInt (ref x);
           Console.WriteLine ("The integer is " + x);
        }
        static void OutInt (out int val)
        {
            val = 42;
        }
        static void ShowInt (int val)
        {
           Console.WriteLine ("The value passed is " + val.ToString());
        }
        static void ChangeInt (ref System.Int32 val)
        {
            val *= 2;
        }
    }
}


System maximums and minimums

using System;
class Test {
  public static void Main() {
       // First, print out the minimum values
       Console.WriteLine("System Minimums\n");
       Console.WriteLine( "MinSByte {0}", System.SByte.MinValue);
       Console.WriteLine( "MinByte {0}", System.Byte.MinValue);
       Console.WriteLine( "MinInt16 {0}", System.Int16.MinValue);
       Console.WriteLine( "MinUInt16 {0}", System.UInt16.MinValue);
       Console.WriteLine( "MinInt32 {0}", System.Int32.MinValue);
       Console.WriteLine( "MinUInt32 {0}", System.UInt32.MinValue);
       Console.WriteLine( "MinInt64 {0}", System.Int64.MinValue);
       Console.WriteLine( "MinUInt64 {0}", System.UInt64.MinValue);
       Console.WriteLine( "MinChar {0}", System.Char.MinValue);
       Console.WriteLine( "MinSingle {0}", System.Single.MinValue);
       Console.WriteLine( "MinDouble {0}", System.Double.MinValue);
       // Console.WriteLine( "MinBoolean {0}", System.Boolean.MinValue);
       Console.WriteLine( "MinDecimal {0}", System.Decimal.MinValue);
    
       Console.WriteLine("\nSystem Maximums\n");
       Console.WriteLine( "MaxSByte {0}", System.SByte.MaxValue);
       Console.WriteLine( "MaxByte {0}", System.Byte.MaxValue);
       Console.WriteLine( "MaxInt16 {0}", System.Int16.MaxValue);
       Console.WriteLine( "MaxUInt16 {0}", System.UInt16.MaxValue);
       Console.WriteLine( "MaxInt32 {0}", System.Int32.MaxValue);
       Console.WriteLine( "MaxUInt32 {0}", System.UInt32.MaxValue);
       Console.WriteLine( "MaxInt64 {0}", System.Int64.MaxValue);
       Console.WriteLine( "MaxUInt64 {0}", System.UInt64.MaxValue);
       Console.WriteLine( "MaxChar {0}", System.Char.MaxValue);
       Console.WriteLine( "MaxSingle {0}", System.Single.MaxValue);
       Console.WriteLine( "MaxDouble {0}", System.Double.MaxValue);
       Console.WriteLine( "MaxDecimal {0}", System.Decimal.MaxValue);
  }
}


Test for an Even or Odd Value

using System;
using System.Data;

class Class1{
        static void Main(string[] args){
           Console.WriteLine(IsEven(0));
           Console.WriteLine(IsEven(3));
           Console.WriteLine(IsOdd(2));
           Console.WriteLine(IsOdd(1));
        }
    public static bool IsEven(int intValue)
    {
      return ((intValue & 1) == 0);
    }
    public static bool IsOdd(int intValue)
    {
      return ((intValue & 1) == 1);
    }
}


Use Integer.Parse to check: is it a number

using System;
using System.Data;
using System.Text.RegularExpressions;
class Class1{
        static void Main(string[] args){
      string IsNotNum = "111west";
      string IsNum = "  +111  ";
      string IsFloat = "  23.11  ";
      string IsExp = "  +23 e+11  ";
      
      Console.WriteLine(IsIntegerRegEx(IsNum));    // True
      Console.WriteLine(IsIntegerRegEx(IsNotNum));  // False
      Console.WriteLine(IsIntegerRegEx(IsFloat));    // False
      Console.WriteLine(IsIntegerRegEx(IsExp));    // False
        }
    public static bool IsIntegerRegEx(string str)
    {
      str = str.Trim();
      return (Regex.IsMatch(str, @"^[\+\-]?\d+$"));
    }
}


Use int.Parse to check: is it an integer

using System;
using System.Data;

class Class1{
        static void Main(string[] args){
      string IsNotNum = "111west";
      string IsNum = "  +111  ";
      string IsFloat = "  23.11  ";
      string IsExp = "  +23 e+11  ";
      
      Console.WriteLine(IsNumeric(IsNum));    // True
      Console.WriteLine(IsNumeric(IsNotNum));    // False
      Console.WriteLine(IsNumeric(IsFloat));    // False
      Console.WriteLine(IsNumeric(IsExp));    // False
      Console.WriteLine();
        }
    public static bool IsNumeric(string str)
    {
      try
      {
        str = str.Trim();
        int foo = int.Parse(str);
        return (true);
      }
      catch (FormatException e)
      {
        Console.WriteLine("Not a numeric value: {0}", e.ToString());
        return (false);
      }
    }
}


Use int variable

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy
Publisher: Sybex;
ISBN: 0782129110
*/
public class Example2_1
{
  public static void Main()
  {
    int count = 1;
    System.Console.WriteLine("count = " + count);
  }
}


Use regualr expression to check: is it a number

using System;
using System.Data;
using System.Text.RegularExpressions;
class Class1{
        static void Main(string[] args){
      string IsNotNum = "111west";
      string IsNum = "  +111  ";
      string IsFloat = "  23.11  ";
      string IsExp = "  +23 e+11  ";
      
      Console.WriteLine(IsNumericRegEx(IsNum));    // True
      Console.WriteLine(IsNumericRegEx(IsNotNum));  // False
      Console.WriteLine(IsNumericRegEx(IsFloat));    // True
      Console.WriteLine(IsNumericRegEx(IsExp));    // False
        }
    public static bool IsNumericRegEx(string str)
    {
      str = str.Trim();
      return (Regex.IsMatch(str, @"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$"));
    }    
}


Use regualr expression to check: Is it an Unsigned Integer

using System;
using System.Data;
using System.Text.RegularExpressions;
class Class1{
        static void Main(string[] args){
      string IsNotNum = "111west";
      string IsNum = "  +111  ";
      string IsFloat = "  23.11  ";
      string IsExp = "  +23 e+11  ";
      
      Console.WriteLine(IsUnsignedIntegerRegEx(IsNum));    // True
      Console.WriteLine(IsUnsignedIntegerRegEx(IsNotNum));  // False
      Console.WriteLine(IsUnsignedIntegerRegEx(IsFloat));    // False
      Console.WriteLine(IsUnsignedIntegerRegEx(IsExp));    // False
        }
    public static bool IsUnsignedIntegerRegEx(string str)
    {
      str = str.Trim();
      return (Regex.IsMatch(str, @"^\+?\d+$"));
    }
    
}


Use regular expression to get number from string

using System;
using System.Data;
using System.Text.RegularExpressions;
class Class1{
        static void Main(string[] args){
      string IsNotNum = "111west";
      string IsNum = "  +111  ";
      string IsFloat = "  23.11  ";
      string IsExp = "  +23 e+11  ";
      
      Console.WriteLine(GetNumberFromStr(IsNum));    // +111
      Console.WriteLine(GetNumberFromStr(IsNotNum));  // 
      Console.WriteLine(GetNumberFromStr(IsFloat));  // 23.11
      Console.WriteLine(GetNumberFromStr(IsExp));    // 
        }
    public static string GetNumberFromStr(string str)
    {
      str = str.Trim();
      Match m = Regex.Match(str, @"^[\+\-]?\d*\.?[Ee]?[\+\-]?\d*$");
      return (m.Value);
    }
    
}