Summary of numeric conversions

Parsing base 10 numbers

Use the Parse and TryParse methods.


using System;
using System.Text;
using System.Globalization;

class Sample
{
    public static void Main()
    {
        double d = double.Parse("3.5");
        int i;
        bool ok = int.TryParse("3", out i);
        
    }
}

Parsing from base 2, 8, or 16 with Convert.ToIntegral


using System;
using System.Text;
using System.Globalization;

class Sample
{
    public static void Main()
    {
        int i = Convert.ToInt32("1E", 16); 
        Console.WriteLine(i);
    }
}

The output:


30

Formatting to hexadecimal: ToString ("X")


using System;
using System.Text;
using System.Globalization;

class Sample
{
    public static void Main()
    {
        string hex = 45.ToString("X"); 
        Console.WriteLine(hex);
    }
}

The output:


2D

Lossless numeric conversion: Implicit cast


using System;
using System.Text;
using System.Globalization;

class Sample
{
    public static void Main()
    {
        int i = 23;
        double d = i;
    }
}

Truncating numeric conversion: Explicit cast


using System;
using System.Text;
using System.Globalization;

class Sample
{
    public static void Main()
    {
        double d = 23.5;
        int i = (int)d;
    }
}

Rounding numeric conversion with Convert.ToIntXXX


using System;
using System.Text;
using System.Globalization;

class Sample
{
    public static void Main()
    {
        double d = 23.5;
        int i = Convert.ToInt32(d);
        Console.WriteLine(i);

    }
}

The output:


24
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.