Convert float to string

Hey all, I’m sure this is common and simple, but I couldn’t find it in the docs…
How do I convert a float to a string.

i.e. the following does not work:

//
var weightfield = GameObject.Find(“WeightField”).GetComponent(“TextMesh”);
weightfield.text = totalWeight;
//

However, if I change it to weightfield.text = “hello”, then hello is displayed.

Thanks for any help!
Cheers,
Will

1 Like

totalWeight.ToString();

7 Likes

Also, you can give it a format string if you want more control over the output. Say, if you want it to only show two digits after the decimal: .ToString("#.00");

I don't know all the options for this, but it's pretty powerful.

5 Likes

Ah! Thank you both very much!

Heh I tried ToString initially but my stupid self forgot the parenthesis.

Cheers,
Will

1 Like

Two years later. But thanks! I used the information.

1 Like


Er... three years? ;-) Even better...

my search page is set to this.

Its the best way to search everything in unity at one time. Super resource! That way I often find things like this thread that can help me.

4 Years? I think I win :smile:

You sad person.

Necrophiliacs the lot of you :smile:

I can’t help the urge! Plus besides the obvious I kept forgetting the parenthesis.

5 years!

make fun with unity !! :smile:

A link which explain how to use the option of ToString() could be usefull ;)

Here you are : http://blog.stevex.net/string-formatting-in-csharp/

to up your ante baz, the MSDN documentation on formatting types:

which has break down links to all the sub data type formats (see bottom in ‘related articles’)

34 years!

LOL 5 years!!!

“”+ totalWeight;

Adding a string even an empty one to a float or int will convert it

finnaly 6 years :smile:

6 years 3 months:smile: