Copy the code code as follows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Javascript rounding (Math.round() and Math.pow())</title>
<script type="text/javascript">
//Math.round(x); Returns the nearest integer of the number, rounding to the integer, that is, discarding the decimal part
function f(){
alert(Math.round(123.567));
alert(Math.round(123.456));
}
//Math.pow(x,y); returns the specified power of the base
//Returns the numerical expression equal to x raised to the y power with x raised to the y power
//If the parameter of pow is too large and causes floating point overflow, return Infinity
function f1(){
alert(Math.pow(2,10));//2 raised to the 10th power is equal to 1024
alert(Math.pow(1024,0.1));//1024 raised to the power of 0.1 is equal to 2
alert(Math.pow(99,9999));//If overflow returns Infinity
}
/*Javascript sets the number of decimal places to be retained and rounded.
*ForDight(Dight,How): Numeric formatting function, the number to be formatted by Dight, and the number of decimal places to be retained by How.
*The method here is to first multiply by a multiple of 10, then remove the decimals, and finally divide by a multiple of 10.
*/
function ForDight(Dight,How){
Dight = Math.round(Dight*Math.pow(10,How))/Math.pow(10,How);
return Light;
}
function f2(){
alert(ForDight(12345.67890,3));//retain three decimal places
alert(ForDight(123.99999,4));//retain four decimal places
}
//Another rounding method, the principle is the same.
//The two parameters inside: num are the data to be converted. n is the number of digits to be converted
//cheng(123.456,2);//retain two decimal places
function cheng(num,n){
vardd=1;
vartempnum;
for(i=0;i<n;i++){
dd*=10;
}
tempnum = num*dd;
tempnum = Math.round(tempnum);
alert(tempnum/dd);
}
</script>
</head>
<body>
<input type="button" value="round" onclick="f();" />
<input type="button" value="pow" onclick="f1();" />
<input type="button" value="Set the number of decimal places to keep and round" onclick="f2();" />
<input type="button" value="cheng" onclick="cheng(123.456,2);" />
</body>
</html>