How can I capture a number by keyboard and take it to a float type variable?

0

Good morning, I understand that when I capture a data by keyboard I should convert it like this:

entero1 = Convert.ToInt32(Console.ReadLine())

Now my question is how can I do it if the data I need is decimal, I try it this way, but the syntax does not allow me to continue.

numero = Convert.ToDouble(Console.ReadLine());
    
asked by jorge 28.08.2017 в 08:46
source

1 answer

2

Do not use the class Convert if you try to parse a text that has been entered by the user because it is possible that the text is not a valid value of the type of data you want to obtain. Instead it uses the TryParse() method of the target data type.

Example with the case of Single (in C # alias float )

C # 7 or higher

if (Single.TryParse(Console.ReadLine(), out float numero))
{
    // Acá la variable numero tiene el valor asignado
}
else
{
    // No se pudo converir el dato ingresado por el usuario en float
}

C # 6 or lower

float result;
if (Single.TryParse(Console.ReadLine(), out numero))
{
    // Acá la variable numero tiene el valor asignado
}
else
{
    // No se pudo converir el dato ingresado por el usuario en float
}

The same can be done in the case of decimal and double , the 3 types of data have the method TryParse()

    
answered by 28.08.2017 в 09:08