x


How to limit calculations to one decimal place?

What I want to do is have a timer on top of the screen counting how long you have been alive. The code for it is simple, and it works:

var aliveTime : float = 0;

function Update () {
    aliveTime += Time.smoothDeltaTime;
    guiText.text = "Time: " + aliveTime;
}

The problem is, it shows 7 places after the decimal. I want it to show just one so it looks like this: 70.7. I do not want it the other way as it is VERY distracting and no need for it to be so precise. I would like to know how to do this as it will help keep track of scores and what not.

more ▼

asked May 16 '10 at 11:13 PM

xToxicInferno gravatar image

xToxicInferno
485 24 28 41

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

2 answers: sort voted first

Use this:

guiText.text = "Time: " + aliveTime.ToString("f1");
more ▼

answered May 16 '10 at 11:48 PM

Eric5h5 gravatar image

Eric5h5
80.3k 42 132 521

Works perfectly! Thank you for that one...and as usual with one problem solved, a dozen more come up!

May 16 '10 at 11:55 PM xToxicInferno

I've been looking for that too for a couple of hours! - thanks a bunch Eric5h5!

Dec 07 '10 at 06:54 PM schwertfisch

sorry to ask a question here, but does f2 mean 2 decimal places, and f3 mean 3 decimal places and so on?

Dec 23 '10 at 05:46 PM Jesus_Freak

Give it a try and see.

Dec 23 '10 at 07:06 PM Eric5h5

I really needed this too! Thanks so much.

Jan 08 '12 at 12:20 AM Pixelen
(comments are locked)
10|3000 characters needed characters left

I think this question was asked a while ago (though QATO doesn't seem to give the year with the date), but in case anyone comes across it:

To round floats to arbitrarily decimal places without converting to strings (as in Eric5h5's solution), you can use (as a general solution):

function round(x, decimalPlaces) {
    return Mathf.Round(x * Mathf.Pow(10, decimalPlaces));
}

If you specifically only ever want one decimal place:

rounded = Mathf.Round(unrounded*10)/10;

Or two:

rounded = Mathf.Round(unrounded*100)/100;

And so on...

(As an aside, you can also use this kind of technique to round to the nearest anything: e.g. to round to nearest interval of 0.3 by using Mathf.Round(x/0.3)*0.3.)

more ▼

answered May 01 '12 at 06:55 PM

Comaleaf gravatar image

Comaleaf
83 3 7 7

I found this to be equally as useful as Eric's suggestion, thank you!, Lauren.

May 23 '12 at 02:29 PM MithosAnnar
(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:

x572
x55

asked: May 16 '10 at 11:13 PM

Seen: 4386 times

Last Updated: Oct 20 '12 at 05:26 AM