Home > Software engineering >  I'm a beginner and write console programs I'm trying to build a calculator and need help (
I'm a beginner and write console programs I'm trying to build a calculator and need help (

Time:12-05

I want to know how to use a user input similar to Convert.ToInt64(Console.Readline()) but if they type e.g.: 198.98

Into the floating point type you prefer var doesn't work I don't know what else to do

CodePudding user response:

you can use this:

float.TryParse(Console.Readline());

CodePudding user response:

You should use this method instead of using the Convert class. If you want to make sure your program doesn't throw an exception, try float.TryParse() instead.

var f = float.Parse(Console.ReadLine());

Console.WriteLine(f);
Console.ReadLine();

CodePudding user response:

You should check the input parameter and then try to cast it. use try parse to cast

    if(double.TryParse(request.Code, out var doubleNumber))
    {
        throw new ArgumentException();
    }

read this doc : https://docs.microsoft.com/en-us/dotnet/api/system.double.tryparse?view=net-6.0

CodePudding user response:

Make sure that the user only can input number.

var a = float.Parse(Console.ReadLine());

Console.WriteLine(a);

Or

double b = Convert.ToDouble(Console.ReadLine());

Console.WriteLine(b);

You can also read this article

https://docs.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/numbers-in-csharp-local

CodePudding user response:

We have various options for performing this conversion. The difference between float and double is that float has four places after the decimal point and double has twelve places after the decimal point. So of you want double you can use it as,

var num = Convert.ToDouble(Console.ReadLine())

In case if you want to convert it into float we have two options there, parse and tryparse. Parse returns the converted number and TryParse returns the Boolean value of conversion. You can use it accordingly like,

var num = float.Parse(Console.ReadLine())

  •  Tags:  
  • c#
  • Related