blog games developers documentation portfolio gallery

More in this category:

Converting to and from string

Here are some simple but handy functions.

To convert a string into an int or a float there is of course the C# functions ToInt32() or ToSingle(), but they immediately throw an exception if the string is not correctly formatted. Personally, I hate this. It forces me to add a try {} catch{} block every time and often I don't even care if the string can be converted to an int or not. Very often a return value of 0 will do just fine in those cases.

So here are the functions that I use for this. They extend the default string class and are easy to use.

using UnityEngine;
using System;
using System.Collections;
using System.Globalization;

namespace MyExtensions
{
public static class StringExtensions
{
public static int MakeInt(this string str) {
int parsedInt = 0;
if(str!=null && int.TryParse(str, out parsedInt)) return parsedInt;
return 0;
}

public static float MakeFloat(this string str) {
float parsedFloat = 0f;
if (str!=null && float.TryParse(str, out parsedFloat)) return parsedFloat;
return 0f;
}
}
}

Here's a function to convert a string to a Vector3, that returns 0,0,0 and logs a message when it can't convert the string. Of course you can also throw an exception instead:

public static Vector3 MakeVector3(this string aStr) {
Vector3 v = new Vector3(0,0,0);
if(aStr!=null && aStr.Length>0) {
try {
if(aStr.IndexOf(",",0)>=0) { // 0.3, 1.0, 0.2 format
int p0 = 0;
int p1 = 0;
int c = 0;
p1 = aStr.IndexOf(",",p0);
while(p1>p0 && c<=3) {
v[c++] = float.Parse(aStr.Substring(p0,p1-p0));
p0=p1+1;
if(p0 < aStr.Length) p1 = aStr.IndexOf(",",p0);
if(p1 < 0) p1 = aStr.Length;
}
}
} catch(Exception e) {
Debug.Log("Could not convert "+aStr+" to Vector3. "+e);
return new Vector3(0,0,0);
}
}
return v;
}


Now the other way around: Converting a value into a string. For an int that is easy, but for a float I like to specify the number of decimals.

public static string MakeString(this float aFloat, int decimals) {
if(decimals<=0) return ""+Mathf.RoundToInt(aFloat);
string format = "{0:F"+decimals+"}";
return string.Format(format, aFloat);
}

You can use this as follows:

string myString = "buy 5 bananas";
int howMany = myString.MakeInt(); // returns 0

string priceString = "5.75";
float howMuch = myString.MakeFloat(); // returns 5.75f

Debug.Log("The price is " + howMuch.MakeString(2));


And the same for converting a Vector3 to a string:

public static string MakeString(this Vector3 v, int decimals) {
if(decimals<=0) return "<" + Mathf.RoundToInt(v.x) + "," + Mathf.RoundToInt(v.y) + "," + Mathf.RoundToInt(v.z) + ">";
string format = "{0:F"+decimals+"}";
return "<"+string.Format(format, v.x)+","+string.Format(format, v.y)+","+string.Format(format, v.z)+">";
}






follow us