The Tech Platform
May 26, 20221 min
Convert class provides different methods to convert a base data type to another base data type. The base types supported by the Convert class are Boolean, Char, SByte, Byte, Int16, Int32, Int64, UInt16, UInt32, UInt64, Single, Double, Decimal, DateTime, and String. It also provides methods that support other conversions. This class is defined under System namespace.
Following is the syntax −
public static bool ToBoolean (string val, IFormatProvider provider);
Val is a string that contains the value of either TrueString or FalseString, whereas the provider is an object that supplies culture-specific formatting information.
It provides methods that are used to convert every base type into every other base type.
It provides methods that are used to convert integer values to the non-decimal string representation, also convert the string represent the non-decimal numbers to integer values.
It provides methods that are used to convert any custom object to any base type.
It provide a set of methods that supports base64 encoding.
An OverFlowException can occur if a narrowing conversion results in a loss of data.
using System;
using System.Globalization;
public class Demo {
public static void Main(){
String val = "876876, 878";
NumberFormatInfo formatProvider = new NumberFormatInfo();
formatProvider.NumberDecimalSeparator = ", ";
formatProvider.NumberGroupSeparator = ".";
formatProvider.NumberGroupSizes = new int[] { 2 };
Console.WriteLine("Converted Decimal value is :");
double res = Convert.ToDouble(val, formatProvider);
Console.Write("{0}", res);
}
}
Output:
using System;
using System.Globalization;
public class Demo {
public static void Main(){
CultureInfo cultures = new CultureInfo("en-US");
String val = "8787";
Console.WriteLine("Converted Decimal value is :");
decimal res = Convert.ToDecimal(val, cultures);
Console.Write("{0}", res);
}
}
Output:
The Tech Platform