How to round a number?

I have a driving game and am displaying the speed in the corner. This is my code

var mph = rigidbody.velocity.magnitude * 2.237;

mphDisplay.text = mph + " MPH";

It works fine except it displays to like 5 decimal points because I converted it to MPH. I need to round it up to .5 and I know I need to use Mathf.Round, I just don’t know how, can anyone help?

If you want to round a number to an integer, Mathf.Round is the thing for you. If you only want to limit the number of significant figures, you can do something like this:

var mph : float = Mathf.Round(rigidbody.velocity.magnitude * 22.37) / 10;
// notice the factor of ten in the bit that gets rounded- adding one decimal point

But that’s pretty hacky. There’s probably a better way in the Float library in .net, but you can look that up yourself if you run into any more trouble.

To display a single digit after the decimal point, you can use the “F1” format:

var mph = rigidbody.velocity.magnitude * 2.237;
mphDisplay.text = mph.ToString("F1") + " MPH"; // displays one digit after the dot

But if you want to display multiples of 0.5, @syclamoth’s idea can do the job with a little change:

var mph: float = Mathf.Round(rigidbody.velocity.magnitude * 2.237 * 2)/2;
mphDisplay.text = mph.ToString("F1") + " MPH"; // displays one digit after the dot