- Home /
Convert a char to int / float
A simple question, how do I convert a char (in this case it comes from a string (content[0])) right in to int or float?
So if the char shows '4', the ints value whould be 4.
Many thanks! :)
This is not a good site for non-Unity questions; you'll find many more knowledgeable programmers at Stack Overflow.
I use int.Parse()
and float.Parse()
. It's $$anonymous$$ORE advised, however, that you use int.TryParse()
and float.TryParse()
unless you are absolutely convinced that you will never have an illegal value enter that variable.
Answer by fafase · Jun 17, 2012 at 11:13 AM
http://msdn.microsoft.com/en-us/library/system.single.tryparse.aspx
Have a look there
It goes like this with Js:
var str:String = "5";
var fl:float;
function Update(){
float.TryParse(str,fl);
fl *= 2;
Debug.Log(fl); // Prints out 10
}
Edit: As required by Benk:
var str:String = "5 and other letters";
var integer :int;
function Update(){
integer = str[0];
integer -=48;
Debug.Log(integer); // Prints out 5
}
The -48 is because 0 is 48 (0x0030) in Unicode value and you need to subtract that value to get the integer representation.
benk0913 : I'm talking about a char variable not a string variable.
Ok, so first off, if you want to convert a char variable, you won't be able to get a float but only a int. char only holds 128 values (ASCII table) and does are all 1 byte only so no possible float. Now, you can get the ASCII value of your char as I show in the edit of my answer.
Well you can get a float, just it won't have any fractional parts.
@fafase - you're right, have deleted my answer, the function was ToInt32(myChar) but it complains the cast doesn't work anyway! $$anonymous$$gest if you want a float to convert your int to a float.
@fafase: char doesn't use ASCII, it's Unicode. It holds 65$$anonymous$$+ values, and it's not a byte.
Answer by Setzer22 · Jun 17, 2012 at 04:33 PM
The .NET method to do that is:
Char.GetNumericValue(randomChar) //randomChar is the char you want to convert
I don't know if this works on UnityScript (assuming it uses the same libraries as C# does, I'll say it should work).
Also, I don't think this is needed, but if this doesn't work, try adding "using System;" (without brackets) at the top of your script.
This works on a Char itself, not an string, which is an array of chars. Although reading chars it's not what you normally want, because a char only represents an alphanumeric value (so, it can only represent the numbers from 0 to 9, you cannot have a char containing 10 or 12).
It's because of that that normally, you want to add some numeric chars into a string so you can convert numbers being greater than 9 into integer variables.
Your answer
Follow this Question
Related Questions
Convert Text to float 3 Answers
Turn float to int 2 Answers
Convert bool to char in C# 3 Answers
Convert string to int C# 1 Answer