- Home /
string to float with f
So i have the following code (all is in C#)
BTW: the xposs is recieved from a server so i cant just say its a float, i need it converted to a float with 0.0f behind:
xposs = "951.9791"
xspawn = float.Parse(yposs);
this just returns 951.9791 in a float but i want 951.9791f
i have also tried:
xposs = "951.9791"
xspawn = float.Parse(yposs) + 0.0f;
this still does not work.
I need it to be 0.0f format becaouse i use it in a Vector3(), and not having the f does not seem to work (well it works but the cordinates are totally wrong, and if i manually press f after it works.)
Answer by Eric5h5 · Jan 04, 2013 at 10:41 PM
A float can't be 951.9791f, it can only be 951.9791. You only add the "f" in a script to tell the compiler that it's a float, but once compiled the number itself does not and cannot contain any letters. float.Parse is correct and returns a float, but your problem seems to be that you are using "xspawn = float.Parse(yposs);" when you should presumably be using "xspawn = float.Parse(xposs);".
Cant confirm that yor statement is true. I will see if i have miss typed the x y z. Ill get back tommorow.
I can confirm that Eric5h5 is not high and 100% correct. The reason a float contains the f at the end is to ensure it doesn't parse as a double. This isn't needed when you float.parse since there is no question that the floating point number is meant to be a float.
It's the same as how you say w="cows";
in the program, but you don't need the quotes when a user enters input, or you say w=w2;
.
The f for float is like the quotes for strings.
EDIT: I assume Landern works at a drug-testing facility. Still, revealing results like that seems unethical.
Actually I have greater respect for Eric with that reply. :)
Answer by Piflik · Jan 04, 2013 at 10:36 PM
No idea if that works, just a spontaneous idea...
xposs = xposs + "f";
xspawn = float.Parse(xposs);
Edit: Nope, doesn't work.
Another edit:
Your code works here. No need for an f...
private string xposs = "951.9791";
private float xspawn;
void Start () {
xspawn = float.Parse(xposs);
print(xspawn);
transform.position = Vector3.zero * xspawn;
}
No it it does not. Unity starts the game, but when the functions is called i get tons of error saying it cant convert f to float :)
How can i put it in this:
New vector3(xposs, yposs, zposs) ?
Would that work?
Answer by Mr.Z · Jan 04, 2013 at 10:47 PM
[http://stackoverflow.com/questions/14166089/c-sharp-string-to-float-with-f][1] [1]: http://stackoverflow.com/questions/14166089/c-sharp-string-to-float-with-fFloats are just a numeric value with type System.Float. They don't have an f behind it. That's just the notation C# uses for float literals. float.Parse returns a float, it's not possible or necessary to add an f.