- Home /
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?
Answer by syclamoth · Apr 20, 2012 at 02:36 AM
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.
Answer by aldonaletto · Apr 20, 2012 at 03:00 AM
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 dotBut 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
How can I use ToString("F1") but hide the dot? for example if the float was 6.9 but i wanted it to display as 69. idk if u will respond because you are sort of a legend to me I see you on so many forums posts but none the less thank you for all the help you have given me in other posts!
so i figured it out.. for anybody who maybe comes by this post looking for the same thing... its:
speedText.text = (runSpeed.ToString("f1")).Replace(".", "");
Your answer
Follow this Question
Related Questions
how to keep speed canstant in flappy bird? 2 Answers
Round to decimals 2 Answers
Accelerate/Decelerate Custom Game Clock 2 Answers
Why does my game run much faster on Windows than Linux 1 Answer
I dont want Decimals :P 1 Answer