x


Round to decimals

Hi,

i wonder if there is a function to round a number to a given number of decimals in javascript. For example, to round 2.543686 to 2.54.

The (10.8).toFixed(2); doesn't work in unity, and .ToString(F2); is converting a number to a string.

Thanks.

more ▼

asked Dec 20 '11 at 02:47 PM

uberwleiss gravatar image

uberwleiss
198 10 14 22

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

1 answer: sort voted first

To be completely honest I don't know for sure. Maybe something like this:

    var randomNumber = 2.543686;

    randomNumber = Mathf.Round(randomNumber * 100.0) / 100.0;

This will round 'randomNumber' to two decimals.

If you want three decimals you can divide by 1000.0.

If you want four decimals you can divide by 10000.0.

And so on.

more ▼

answered Dec 20 '11 at 02:52 PM

OrangeLightning gravatar image

OrangeLightning
5.4k 47 57 113

Thanx! Haven't thought of that.

Dec 20 '11 at 03:18 PM uberwleiss
(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:

x24
x24
x5

asked: Dec 20 '11 at 02:47 PM

Seen: 1540 times

Last Updated: Dec 20 '11 at 03:18 PM