C# String to float with f

2019-09-24 15:16发布

问题:

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

回答1:

f postfix is applied only to literals in code. It is used to denote literal values as float. If no postfix is present - literal value will be of type double

you can pass the result of float.Parse(stringValue) into Vector3 and Vector2 as constructor arguments in Unity 3d The next code create a Vector3 object with x y z equal to value set in string

string sideSize = "12.5";
float vectorSide = float.Parse(sideSize, CultureInfo.InvariantCulture);
Vector3 resultVector = new Vector3(vectorSide, vectorSide, vectorSide); //create vector3 with x = y = z = 12.5


回答2:

the "f" suffix is supplied in literal values to denote the data type

  • f for float
  • m for decimal
  • d for double


回答3:

Floats are just a numeric value with type System.Single. 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.