Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JavaScript Math function 1

Status
Not open for further replies.

khue

Programmer
Mar 6, 2001
112
US
Does anyone know if javascript have a math function that will round a floating decimal number to the tenth, hundredth...etc., position? The Math.Round() rounds it to an integer. I don't want an integer.
 
Hey,

Not sure if this will work but...If you want your float rounded to (for example) 2 decimal places why not:

(1) multiply the float by 100
(2) use Math.Round() to round it to an integer
(3) divide it by 100

You could have a function:

function myRound( number, places ) {
return (Math.Round(number*(10^places)))/(10^places)
}

Hope that helps,

Gus
 
for some reason the ^ operator isn't always an Math operator... it's also a bitwise exclusive or operator. this is what i use.

Number.prototype.toDec = function(p)
{
var x = Math.pow(10, p);
var y = Math.round(this * x)/x;
return y;
}


you use it like this:

var y = 100.7896;
y = y.toDec(2);
alert(y);

y will be 100.79

the above function won't round to decimals place if it doesn't have enough digits... so, i use this function... it returns a string, but, it's the only way to format a number with extra 0's on the end.

Number.prototype.toDec = function(e)
{
var x, y, boo, bo;
x = Math.pow(10,e);
y = new String(Math.round(this * x)/x);
boo = (y.indexOf(".") > -1)?(y.split(".")[1].length == e)?false:true:true;
if(boo)
{
bo = (y.indexOf(".") > -1)?false:true;
if(bo){y+=&quot;.&quot;;for(var i = 0; i < e; i++){y+=&quot;0&quot;;}}
else
{
boo = e - y.split(&quot;.&quot;)[1].length;
for(var i = 0; i < boo; i++){y+=&quot;0&quot;;}
}
}
return y;
} luciddream@subdimension.com
 
this line wrapped... it should be all one line:

boo = (y.indexOf(&quot;.&quot;) > -1)?(y.split(&quot;.&quot;)[1].length == e)?false:true:true;
luciddream@subdimension.com
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top