您的位置:首页 > Web前端 > JavaScript

小数四舍五入JS保留小数点(四舍五入、四舍六入)实例

2013-04-24 21:43 148 查看
在本文中,我们主要介绍小数四舍五入的内容,自我感觉有个不错的建议和大家分享下

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.01Transitional//EN"> <html> <head> <title>floatDecimal.html</title> <metahttp-equiv="keywords"content="keyword1,keyword2,keyword3"> <metahttp-equiv="description"content="thisismypage"> <metahttp-equiv="content-type"content="text/html;charset=gb2312"> <scripttype="text/javascript"> //保存两位小数 //功能:将浮点数四舍五入,取小数点后2位 functiontoDecimal(x){ varf=parseFloat(x); if(isNaN(f)){ return; } f=Math.round(x*100)/100; returnf; } //制保存2位小数,如:2,会在2前面补上00.即2.00 functiontoDecimal2(x){ varf=parseFloat(x); if(isNaN(f)){ returnfalse; } varf=Math.round(x*100)/100; vars=f.toString(); varrs=s.indexOf('.'); if(rs<0){ rs=s.length; s+='.'; } while(s.length<=rs+2){ s+='0'; } returns; } functionfomatFloat(src,pos){ returnMath.round(src*Math.pow(10,pos))/Math.pow(10,pos); } //四舍五入 document.writeln("保存2位小数:"+toDecimal(3.14159267)+'<br/>'); document.writeln("强制保存2位小数:"+toDecimal2(3.14159267)+'<br/>'); document.writeln("保存2位小数:"+toDecimal(3.14559267)+'<br/>'); document.writeln("强制保存2位小数:"+toDecimal2(3.15159267)+'<br/>'); document.writeln("保存2位小数:"+fomatFloat(3.14559267,2)+'<br/>'); document.writeln("保存1位小数:"+fomatFloat(3.15159267,1)+'<br/>'); //五舍六入 document.writeln("保存2位小数:"+1000.003.toFixed(2)+'<br/>'); document.writeln("保存1位小数:"+1000.08.toFixed(1)+'<br/>'); document.writeln("保存1位小数:"+1000.04.toFixed(1)+'<br/>'); document.writeln("保存1位小数:"+1000.05.toFixed(1)+'<br/>'); //学科数计 document.writeln(3.1415.toExponential(2)+'<br/>'); document.writeln(3.1455.toExponential(2)+'<br/>'); document.writeln(3.1445.toExponential(2)+'<br/>'); document.writeln(3.1465.toExponential(2)+'<br/>'); document.writeln(3.1665.toExponential(1)+'<br/>'); //确精到n位,不含n位 document.writeln("确精到小数点第2位"+3.1415.toPrecision(2)+'<br/>'); document.writeln("确精到小数点第3位"+3.1465.toPrecision(3)+'<br/>'); document.writeln("确精到小数点第2位"+3.1415.toPrecision(2)+'<br/>'); document.writeln("确精到小数点第2位"+3.1455.toPrecision(2)+'<br/>'); document.writeln("确精到小数点第5位"+3.141592679287.toPrecision(5)+'<br/>'); </script> </head> <body> ThisismyHTMLpage.<br> </body> </html> from:http://www.ok12.net/js/86.html
每日一道理

翻开早已发黄的页张,试着寻找过去所留下的点点滴滴的足迹。多年前的好友似乎现在看来已变得陌生,匆忙之间,让这维持了多年的友谊变淡,找不出什么亲切感,只是偶尔遇上,淡淡地微笑,如今也只能在这发黄的页张中找寻过去的那些让人难忘的,至少我可以握住这仅剩下一段的“丝线头”……


文章结束给大家分享下程序员的一些笑话语录:Bphone之你们聊,我先走了!移动说:我在phone前加o,我叫o缝;苹果说:我在phone前i,我是i缝;微软说:我在phone前加w,我叫w缝;三星说:你们聊,我先走了!

将来王建宙写回忆录的时候,一定要有一句“常小兵为中国移动的发展做出了不可磨灭的贡献”。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: