This question already has answers here:
Converting a string to a float data type
(4 answers)
Closed 3 years ago.
So I am trying to have input and output in float number.
Console.WriteLine("Enter float number: ");
float number = Console.ReadLine();
Console.WriteLine("{0}", number);
I see the problem that ReadLine will have format in string which will cause "Error CS0029: Cannot implicitly convert type 'string' to 'float' (CS0029)". Now, how do I convert string to float? I could use float.Parase:
string unformattedNumber;
float number;
Console.WriteLine("Enter float number: ");
unformattedNumber = Console.ReadLine();
number = float.Parse(unformattedNumber);
Console.WriteLine("{0}", number);
But is there any better way to convert in same line as ReadLine statement is at?
TryParse is the best way.
See: http://msdn.microsoft.com/en-us/library/system.single.tryparse.aspx
float number = float.Parse(Console.ReadLine()); should work perfectly fine. In general you can compose function calls like that on the same line. Just don't get carried away -- make sure the meaning's clear. Sometimes it actually makes your code clearer, but if you do it too much, you end up with an unreadable thicket of code.
The problem with calling float.Parse is that if your input isn't a numeric value it will raise an exception and halt your program. As the user can enter anything at this point, you need to cater for that.
You could wrap the float.Parse in an exception handler but it would be better to use float.TryParse:
float result;
if (float.TryParse(Console.ReadLine(), out result))
{
// Do stuff
}
Related
This question already has answers here:
Cannot implicitly convert type 'double' to 'int'. -error
(4 answers)
Closed 9 months ago.
I am a beginner in C#. I'm currently trying to concatenate int data and using the Math square root function, but after running the program, it produces an error.
The code are as follows.
using System;
namespace NewProject
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Type any number");
int number = Convert.ToInt32(Console.ReadLine());
int square_root = Math.Sqrt(number);
Console.WriteLine("$The square root of {square_root} is " , square_root);
}
}
}
C:\Users\ajmal\Documents\Learn C#\New Project\Program.cs(13,31): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) [C:\Users\ajmal\Documents\Learn C#\New Project\N
ew Project.csproj]
The build failed. Fix the build errors and run again.
Any tips and help would be appreciated
The compiler message tells:
Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
It even gives you the location of the error:
New Project\Program.cs(13,31)
Line 13, position 31
If you look there, not very far you should find this line:
int square_root = Math.Sqrt(number);
If you look that the Math.Sqrt documentation, you'll see that Math.Sqrt returns a double.
Here is the signature from the documentation:
public static double Sqrt (double d);
So you try to put a double into an int (the type of your square_root variable), which is only possible with an explicit cast, hence the compiler message.
To fix this (supposing you want to keep a non integer value for the square root) simply correct the line with
double square_root = Math.Sqrt(number);
or you can even let the compiler do the work by leveraging the var keyword:
var square_root = Math.Sqrt(number);
Additional remarks:
The Math.Sqrt signature shows that a double is needed as parameter, but you pass an int. This is not a problem since the compiler can do an implicit conversion from an int to a double.
There will also be an error on the following line (without even considering the meaning of what you write).
Console.WriteLine("$The square root of {square_root} is " , square_root);
To concatenate strings, you can use several techniques, like composite formating and string interpolation. It seems you mix both synthax on this line.
See the string interpolation documentation:
an example of both methods taken from the documentaion:
string name = "Mark";
var date = DateTime.Now;
// Composite formatting:
Console.WriteLine("Hello, {0}! Today is {1}, it's {2:HH:mm} now.", name, date.DayOfWeek, date);
// String interpolation:
Console.WriteLine($"Hello, {name}! Today is {date.DayOfWeek}, it's {date:HH:mm} now.");
// Both calls produce the same output that is similar to:
// Hello, Mark! Today is Wednesday, it's 19:40 now.
I have a CSV with the following data (no header)
12,2010,76.5
2,2000,45
12,1940,30.2
and I'm reading the data into a List<List<object>>.
To know what's in each line and column / row I'm using the following loop
List<List<object>> data = CSVReaderNoHeader.Read("input")
for (var i = 0; i < data.Count; i++)
{
double month = (double)(int)data[i][0];
print($"month:{month} ////END");
double year= (double)(int)data[i][1];
print($"year:{year} ////END");
double temperature= (double)data[i][2];
print($"temperature:{temperature} ////END");
}
Yes I need to create doubles, that's why I'm unboxing and casting (could have use double.Parse instead).
I'm able to print the month and the year just fine, but when reaching double temperature= (double)data[i][2];, throws the following error
InvalidCastException: Specified cast is not valid.
I printed what's in data[i][2] before that line (print(data[i][2]);) just to see if everything was in order there and got 76.5 as expected. Then, tested also using
double temperature= (double)(double)data[i][2];
double temperature= (double)(float)data[i][2];
(which i think it would be unnecessary to add that extra (double) / (float)) and
object tempr = data[i][2];
double temperature;
temperature = (double)tempr;
but the problem remained. So, I went on and ran print(data[i][2].GetType()); to see if the type returned there could be cast into a double. I got as result System.String.
Knowing this, then I tried then the methods double.TryParse, double.Parse and Convert.ToDouble but none worked
double.TryParse(data[i][2], out temperature);
Argument 1: cannot convert from 'object' to string.
double temperature = double.TryParse(data[i][2]);
Argument 1: cannot convert from 'object' to string.
double temperature = System.Convert.ToDouble(data[i][2]);
FormatException: Input string was not in a correct format.
How then I have to cast it?
Because your numbers use a point as decimal separator and your system localization can use a different, you can use that:
using System.Xml;
double temperature = XmlConvert.ToDouble(data[i][2].ToString());
It will raise an exception in case of parsing error.
So you can try...catch to manage it.
Perhaps you will need to add System.Xml to assembly references of the project.
Else you can use #Fabjan solution:
if (double.TryParse(data[i][2].ToString(),
System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture,
out var temperature);
IsOk();
else
IsNotOk();
Why this code won't compile without throwing an exception???
I am trying to convert float test to a character from ASCII table.
float test = 42.5F;
char convertFloatToChar = Convert.ToChar(test);
Console.WriteLine(convertFloatToChar);
All you need is a string:
float test = 42.5F;
String convertFloatToString = Convert.ToString(test);
Console.WriteLine(convertFloatToString);
If you check the overload for Convert.ToChar() then you will see that the exception is logical. You cannot have a float/double in Convert.ToChar() method.
ToChar(Double)
Calling this method always throws InvalidCastException.
You are probably looking for
float test = 42.5F;
String convertFloatToChar = Convert.ToString(test);
Console.WriteLine(convertFloatToChar);
I've just tried TryParse, and am new to C# and just trying to understand everything, and then hopefully best practices...
Syntactically this works:
double number = Double.Parse(C.ReadLine());
Does TryParse only return a boolean, true if parse succeeds?
When I do this:
double number;
bool b = Double.TryParse(C.ReadLine(), out number);
number is the parsed input, from C.ReadLine(), as expected, everything works. Is this how TryParse is normally used? Trying to be efficient, appreciate advice like this.
Any advice on approach welcome, plus info on online resources for Try(things).
You use TryParse when it may fail, and you don't want your code to throw an exception.
For example
if (!Double.TryParse(someinput, out number))
{
Console.WriteLine("Please input a valid number");
}
Parse will return the double value if it succeeds and throws an exception otherwise. TryParse will return a boolean value representing the success of the operation and if it does succeed, it fills in the parsed value in the out argument you pass to it. It will never throw an exception.
In general, you should use TryParse when you expect the input string to not be a valid number and you have the logic to handle it (and display an error message, for instance).
If you don't expect the input string to be anything except a valid double you should use Parse.
The only differnce is that TryParse won't thow an exception if it can't parse the double.
This is handy when you want to assign a default value or ignore the value in your code
Example:
double number;
if (Double.TryParse(C.ReadLine(), out number))
{
// this is a double so all good
}
else
{
// not a valid double.
}
Example:
double number;
progressBar.Value = Double.TryParse(C.ReadLine(), out number) ? number : 4.0;
// If number is a valid double, set progressbar, esle set default value of 4.0
You also asked aboy TyrParse on Enum, this can be done like this
DayOfWeek fav;
if (Enum.TryParse<DayOfWeek>(Console.ReadLine(), out fav))
{
// parsed
}
I have the following code:
int a = 50;
float b = 50.60f;
a = int.Parse(b.ToString());
On run time this parsing gives as error. Why it is please guide me.
Thanks
It's trying to parse the string "50.6" - that can't be parsed as an integer, because 50.6 isn't an integer. From the documentation:
The s parameter contains a number of the form:
[ws][sign]digits[ws]
Perhaps you want to parse it back as a float and then cast to an integer?
a = (int) float.Parse(b.ToString());
This is because int.Parse throws NumberFormatException if the string does not contain a parsable integer; 50.6 is not a prasable integer.
You are trying to parse a string that does not represent an integer into an integer.
This is why you are getting an exception.
It gives an error because you are trying to parse as int a string representing a float.
float b = 50.60f; // b = 50.6
// b.ToString() = "50.6" or "50,6" depending on locale
// int.Parse("50.6") MUST give an error because "50.6" is
// not a string representation of an integer
What is it that you want to do? Convert a float to an int? Just do this:
float b = 50.6f;
int a = (int)b;
That will truncate the value of b to simply 50.
Or do you want it rounded off to the nearest integer?
int a = (int)Math.Round(b);
Is the error message not specific enough?
Input string was not in a correct format.
int.Parse must take a string which can be parsed to an integer. The string "50.6" does not fulfil that requirement!