Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimals to one decimal place in as3?

I randomly generate a decimal using:

private function randomNumber(min:Number, max:Number):Number
    {
        return Math.random() * (max - min) + min;
    }

It comes out with something like 1.34235346435.

How can I convert it so that its 1.3.

like image 602
panthro Avatar asked Nov 30 '22 23:11

panthro


2 Answers

You can round to one decimal place like this;

var newValue:Number = Math.round(oldValue * 10)/10

Or an arbitrary number of decimal places like this:

function round2(num:Number, decimals:int):Number
{
    var m:int = Math.pow(10, decimals);
    return Math.round(num * m) / m;
}
trace(round2(1.3231321321, 3)); //1.323
like image 106
Jonatan Hedborg Avatar answered Dec 09 '22 11:12

Jonatan Hedborg


Just use the .toFixed or .toPrecision method, it doesn't have to be complicated (note that the number will become a string so you'll need to assign it to such or convert it back).

eg.

    var numb:Number = 4.3265891;
    var newnumb;

    newnumb=numb.toFixed(2);//rounds to two decimal places, can be any number up to 20
    trace(newnumb);//traces 4.33

    newnumb=numb.toPrecision(3);//the 3 means round to the first 3 numbers, can be any number from 1 to 20
    trace(newnumb);//traces 4.33
like image 38
Hioctane321 Avatar answered Dec 09 '22 09:12

Hioctane321