Copy codeThe Code is 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, rounded to an integer, that is, 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 number.
// Returns a numeric expression with the y Power of x, equivalent to the y Power of x.
// If the pow parameter is too large and causes floating point overflow, Infinity is returned.
Function f1 (){
Alert (Math. pow (1024); // The 10th power of 2 equals
Alert (Math. pow (1024, 0.1); // The Power of 1024 equals 2
Alert (Math. pow (99,9999); // Infinity is returned if the overflow occurs.
}
/* Set the number of decimal places to be retained in Javascript.
* ForDight (Dight, How): a numeric Formatting Function. It refers to the number to be formatted and the number of decimal places to be retained.
* The method here is to multiply the number by a factor of 10, remove the decimal number, and then divide the number by a factor of 10.
*/
Function ForDight (Dight, How ){
Dight = Math. round (Dight * Math. pow (10, How)/Math. pow (10, How );
Return Dight;
}
Function f2 (){
Alert (ForDight (12345.67890, 3); // retain three decimal places
Alert (ForDight (123.99999, 4); // retain four decimal places
}
// Another rounding method has the same principle.
// Two parameters: num is 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 ){
Var dd = 1;
Var tempnum;
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 = "sets the number of decimal places to be retained, rounded to" onclick = "f2 ();"/>
<Input type = "button" value = "cheng" onclick = "cheng (123.456, 2);"/>
</Body>
</Html>