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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With