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);
Related
I was working on a code and got an issue. What I'm trying to do is to use InputField in unity, then use that number to multiply by existing float. Here's what I got so far:
private float finePrice = 0.0001f;
public InputField enterValue;
public Text estimatedValue;
estimatedValue.text = string.Format ("{0}", finePrice * enterValue);
Error I'm getting:
Operator `*' cannot be applied to operands of type `float' and `UnityEngine.UI.InputField'
In my understanding is that I cannot multiply string (inputfield) to float? I tried changing Content Type of Input Field to "Decimal Number" but I'm getting the same error. Tried googling it, nothing to be found. Please help? I'm lost.
You need to get the content of the InputField using the text property, and then convert that content to float because it's a string:
private float finePrice = 0.0001f, valueEntered;
public InputField enterValue;
public Text estimatedValue;
if(float.TryParse(enterValue.text, out valueEntered))
{
estimatedValue.text = (finePrice * valueEntered).ToString();
}
else
{
estimatedValue.text = "Please enter a float value";
}
Note I've used float.TryParse so that if the user entered a value that can't be converted to float you will simply get false instead of an exception you would get if you used float.Parse. Also, I've changed your string.Format to simply ToString - There is no point of using string.Format in cases like this.
Like Zohar mentioned, InputField.text is a string and you need to convert that to float before you multiply it with your other float.
I left my own answer because I think it's better to use float.Parse to make that conversion and pass in CultureInfo.InvariantCulture.NumberFormat to the second parameter as you don't know what culture the user's device is set to.
Convert InputField value to float
float inputInFloatFormat = float.Parse(enterValue.text, CultureInfo.InvariantCulture.NumberFormat);
Multiply by your float finePrice variable
float multiplyResult = inputInFloatFormat * finePrice;
Display result on your text component(Convert multiplyResult to string) then display it
estimatedValue.text = multiplyResult.ToString();
I have following extension methods, one for float and one for double.
public static string ToTimeString(this float f, TimeStringAccuracy accuracyFlags = DefaultAccuracyFlags, TimeStringSeparator separator = DefaultSeparator)
public static string ToTimeString(this double d, TimeStringAccuracy accuracyFlags = DefaultAccuracyFlags, TimeStringSeparator separator = DefaultSeparator)
When i call the functions from Visual Studio unit tests the tests run correctly and the call is not ambiguous. When i call the functions from Unity3D code for float (using Mono) the call is ambiguous between these two. Why doesn't the compiler know that it should be calling the float extension? Might it be Mono causing this?
This is the call:
float i = 1f;
i.ToTimeString();
Compiler error:
Assets/Scipts/UIScripts/GameplayUIWindow.cs(61,48): error CS0121: The call is ambiguous between the following methods or properties: ToTimeString(this double, TimeStringAccuracy, TimeStringSeparator)' and `ToTimeString(this float, TimeStringAccuracy, TimeStringSeparator)'
Try this version instead:
public static string ToTimeString<T>(this T target, TimeStringAccuracy accuracyFlags = DefaultAccuracyFlags, TimeStringSeparator separator = DefaultSeparator) where T : struct
It may compile to different code in Mono but still allow you to use the code in the way you want. As a disclaimer, I recommend doing some type checking on the type parameter T inside of the method body to guarantee that the method behaves the way you expect for expected types (such as float and double) and throws exceptions for unexpected types (such as int or Enum).
How do I make If statements using floats? The code I have is as follows:
{float p1 = float.Parse(textBox1.Text);
if (p1 == ""){MessageBox.Show("Home");}}
The p1 if statement on the second line does not work. How do I make a proper if statement for this?
EDIT: I should explain. The goal is to check for an empty box. I can't use a string command since I want this to interpret numbers.
Thanks in advance for the help.
float values cannot be "empty". If you try parsing an empty string into a float, you would get a runtime error.
You need to check the string for being empty before parsing, and then parse with a more "conservative" TryParse method that does not throw an exception.
if (string.IsNullOrWhitespace(textBox1.Text)) {
MessageBox.Show("Home");
}
float p1;
if (!float.TryParse(textBox1.Text, out p1)) {
MessageBox.Show("textBox1 is not a float");
}
Note: In general, comparing floats for equality with == operator is not a good idea, because float is not an exact representation. This Q&A discusses the problem in Java, but the issue is relevant in all languages that use floating point representation.
If you are attempting to check whether or not it was able to successfully parse a float value from textBox1.Text, use TryParse instead like so:
float p1;
if (float.TryParse(textBox1.Text, out p1))
{
MessageBox.Show("Home");
}
If you're simply trying to check for an empty text box, you could do this instead:
if (!String.IsNullOrEmpty(textBox1.Text))
{
// Now we can try to parse p1 (assuming it's a valid number)
float p1 = float.Parse(textBox1.Text);
MessageBox.Show("Home");
}
Note that you would also have to handle invalid characters this way (such as letters, symbols, or spaces).
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!
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
}