View Full Version : Round off decimals easily?
flesh
August 14th, 2007, 08:56 AM
As the title, is there a class method in Flash to limit and round of a number's decimals ?
Like :
roundToTwoDecimals(1.2362 ) = 1.24
Thanks in advance fellow flashers!
BradLee
August 14th, 2007, 10:51 AM
Just multiply the number by 10 * the number of decimal places you want to round to, use Math.round, and then divide by the same number... sorta like this:
var tNum:Number = 1.2362 * 100; // equals 123.62
tNum = Math.round(tNum); // gives you 124
tNum = tNum / 100; //gives you 1.24
mathew.er
August 14th, 2007, 12:38 PM
There is no function to do that I think... you can try writing on though
function round ( value : Nuber, decimalPlaces : int ) : Number
{
var k : int = Math.pow ( 10, decimalPlaces );
value *= k;
value = Math.round ( value );
return value / k;
}// edit : I should have refreshed the page first :D
flesh
August 14th, 2007, 01:29 PM
Thanks! both of you!
Slick solution mathew.er ! now I understand the Math.pow too
Krilnon
August 14th, 2007, 06:09 PM
See also: http://www.kirupa.com/forum/showpost.php?p=2057944&postcount=19
TheCanadian
August 14th, 2007, 07:39 PM
The Number class in AS3 has a built in method for rounding numbers to a certain decimal place.
var num:Number = 1.2362;
trace(num.toFixed(2)); //1.24
Note, however, that toFixed returns a String and thus if you want to use the returned value in some mathematical operation, you will have to convert it back to a Number.
flesh
August 16th, 2007, 05:26 PM
Even better!
Thanks!
tedc
October 16th, 2008, 06:58 PM
Even better!
Thanks!
This is super helfpul, but for anyone who stumbled across this in the searches, remember this function returns a STRING not a number so typically you will want to cast like so:
var tempNum:Number = 1.1268;
trace(Number(tempNum.toFixed(3)));
tedc
June 4th, 2009, 07:33 PM
just realized like 8 months after this post that the Canadian had already advised on this functions return value as a string : / duh!
Powered by vBulletin® Version 4.1.10 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.