- Home /
The question is answered, right answer was accepted
Split a number?
Hi
I've been looking through the answers and forums and various javascript and Mono documentation. But I just don't understand.
How do I split a 3 digit number into an array of 3 digits?
I know I should use something like:
var conP : float = 0.00;
function Update () {
var confP : String = conP.ToString();
var arr: Array [];
arr = (confP.Split(""[0]));
Debug.Log(" split = " + arr[0]);
for (var s in arr) Debug.Log (" s = " + s);
}
But it just doesn't work. I know there's lots of stuff out there on it. But I just don't understand. Can someone please explain it in simple terms.
By the way I'm using Unity java script.
Thanks.
Answer by Yokimato · Apr 15, 2013 at 02:45 PM
float number = 0.00;
List<int> digits = new List<int>();
foreach(var digit in number.ToString().ToCharArray()) {
if(digit != '.') {
digits.Add((int)digit);
}
}
I wrote it in C#, as I'm blanking on some of the unity script, however, I'm confident you'll be able to do the conversion.
Here's with an array:
float number = 0.00;
char[] numberChars = number.ToString().ToCharArray();
int[] digits = new int[numberChars.length];
for(int i = 0; i < numberChars.length; i++) {
if(numberChars[i] != '.') {
digits[i] = (int)numberChars[i];
}
}
// as you loop through digits, you'll need to check for nulls (aka. null == decimal point)
Thanks Yokimato!
From your c# scripts I pieced together this:
function Update () {
digits.Clear();
cP = ExternalScript.astaticvariable;
if (cP != cPold) {
var conPtoInt: int = $$anonymous$$athf.RoundToInt(cP);
var conPtoStr: String = conPtoInt.ToString("000");
for (var digit in conPtoStr.ToCharArray()) {
digits.Push(digit);
Debug.Log ("digit = " + digit);
Debug.Log ("digits = " + digits );
}
Debug.Log ("digit[1] = " + digits[0]);
Debug.Log ("digit[2] = " + digits[1]);
Debug.Log ("digit[3] = " + digits[2]);
}
cPold = cP;
}
I decided to drop the decimal and convert the float to an integer. Is this the correct proceedure. that is to clear the arrawy each cycle?