Get data from InputField and Multiply by Float? (Unity/C#) - c#

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();

Related

Making An Object Move C#

I'm making a game in c# and I'm trying to make my texture move. I need some help and advice to make the texture move. This is what I've used so far.
public float InitialTime { get; set; }
public Vector2 InitialPosition { get; set; }
public Vector2 InitialVelocity { get; set; }
public Vector2 Position(GameTime time)
{
float t = (float)time.TotalGameTime.TotalSeconds = InitialTime;
return InitialPosition + t * InitialVelocity;
}
on the 'float t' line, it comes up with the following error,
Error CS0131 The left-hand side of an assignment must be a variable,
property or indexer
Your problem is because of this:
float t = (float)time.TotalGameTime.TotalSeconds = InitialTime;
Both sides of an assignment operation need to have valid syntax. If you were to isolate the second assignment, it would look like this:
(float)time.TotalGameTime.TotalSeconds = InitialTime;
Which is not only invalid syntax, but it also makes little sense.
I imagine that the reason you are doing the cast is because TotalSeconds and InitialTime are doubles and you need to cast them to a float. There are two ways to accomplish this.
You can either split up the assignment onto two different lines:
time.TotalGameTime.TotalSeconds = InitialTime;
float t = (float)time.TotalGameTime.TotalSeconds;
Or, if you insist on doing this on a single line, use parentheses to group your operations:
float t = (float)(time.TotalGameTime.TotalSeconds = InitialTime);
EDIT:
Then again, I've been assuming that the double assignment was intentional. What you may have meant to do was to subtract InitialTime from your TotalTime to get the current time stamp. In that case, it's just a simple fix of a typo:
float t = (float)(time.TotalGameTime.TotalSeconds - InitialTime);
(Note that if TotalSeconds and InitialTime are doubles, you will need to use parentheses to cast the operation to a float, as I have done.)

Not able to Convert float to Char in C#

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);

If Statement for Floats?

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).

Error 1 Invalid expression term 'double'

private void buttonConvert_Click(object sender, EventArgs e)
{
//Convert number from C to F
double convertDecimal;
convertDecimal = 1.8;
textBoxF = double.Parse(textBoxC.Text) * double(convertDecimal) + 32;
^here is where I get the error
Error 1 Invalid expression term 'double'
I am pretty new to programming and but I just can't wrap my mind around trying to add, subtract, dividing, or multiplying numbers. I am trying to do a simple a simple conversion. Take the number from the Celsius textbox and convert it to Fahrenheit. I just don't understand the number part???
Thanks for your help!
double(convertDecimal) should be (double)convertDecimal
That looks like a C++ type-casting expression, which doesn't work in C#. And as convertDecimal already is of type double there's no need to cast it. Just use it directly:
textBoxF = double.Parse(textBoxC.Text) * convertDecimal + 32;
You only need to change the type of a variable (i.e. type-cast) when the variable is of a type not expected. Adding two double values is okay. Even adding a double and an int is okay because the integer is implicitly converted to a double.
Edit: You try to assign the result of the expression to a control, which will not work. You should convert the result to a string (e.g. with double.ToString), and then assign to the controls text field:
double farenheit = double.Parse(textBoxC.Text) * convertDecimal + 32;
textBoxF.Text = farenheit.ToString();

error on int.Parse()

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!

Categories

Resources