Cast Floats to Strings

I want to display the actual numerical health above a health bar, but I can’t find in the Script References a way to cast floats to strings so that you can use them in a GUI element. How do I do that?

Use the ToString () function.

var num : float = 25.402;
Debug.Log (num.ToString ());

In the case of floats especially, you’ll probably want some control over the formatting.

If you have: 5823.3810384

But want to display: 5,823.38

You can use: String.Format(“{0:#,0.00}”, yourNumber))

The particulars of the formatting mean to use commas if the number is above 1,000, pad with a leading zero (so .23 is 0.23), and pad with two ending zeroes (so 1 is 1.00).

If you want to set it up so 1.00 is still displayed as 1, but 1.2345 would be 1.23, you can use the placeholder # instead of 0s, like: String.Format(“{0:#,0.##}”, test))

Generally you’ll want to pad so you get consistent width on display as numbers change.

Hope this helps!