x


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?

more ▼

asked Apr 20 '12 at 02:30 AM

Fitty_Spenc gravatar image

Fitty_Spenc
30 5 6 7

(comments are locked)
10|3000 characters needed characters left

2 answers: sort voted first

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.

more ▼

answered Apr 20 '12 at 02:36 AM

syclamoth gravatar image

syclamoth
14.8k 7 15 80

(comments are locked)
10|3000 characters needed characters left

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
more ▼

answered Apr 20 '12 at 03:00 AM

aldonaletto gravatar image

aldonaletto
41.5k 16 42 197

Thanks thats super helpful

Apr 20 '12 at 03:10 AM Fitty_Spenc
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x798
x357
x24
x23
x14

asked: Apr 20 '12 at 02:30 AM

Seen: 723 times

Last Updated: Apr 20 '12 at 03:10 AM