viernes, 7 de noviembre de 2014

C# - How to convert a string to a number (9 different types of number)



We'll split the example depending on the type of number we want to convert:

A string representing an integer number can be converted to the following types:



String strI = "27";
short ns = Convert.ToInt16(strI);
int ni = Convert.ToInt32(strI);
long nl = Convert.ToInt64(strI);
ushort nus = Convert.ToUInt16(strI);
uint nui = Convert.ToUInt32(strI);
ulong nul = Convert.ToUInt64(strI);

A string representing a decimal number can be converted to the following types:

String strD = "3.1416";
decimal ndec = Convert.ToDecimal(strD);
float nf = Convert.ToSingle(strD);
double nd = Convert.ToDouble(strD);



If you try to convert a number outside the rules described, you'll get an error.

No hay comentarios.:

Publicar un comentario