<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
(function($){
$.extend({
//将浮点数四舍五入,取小数点后2位
changeTwoDecimal:function(floatvar) {
var num = parseFloat(floatvar);
if (isNaN(num)) {
alert(‘parameter is error‘);
return false;
};
num = Math.round(num * 100) / 100;
return num;
},
//强制保留2位小数
changeTwoDecimal_f:function(floatvar) {
var num = parseFloat(floatvar);
if (isNaN(num)) {
alert(‘parameter is error‘);
return false;
};
num = Math.round(num * 100) / 100;
var s_num = num.toString();
var pos_decimal = s_num.indexOf(‘.‘);
if (pos_decimal < 0) {
pos_decimal = s_num.length;
s_num += ".";
while(s_num.length <= pos_decimal + 2) {
s_num += ‘0‘;
};
} else {
while(s_num.length <= pos_decimal + 2) {
s_num += ‘0‘;
};
};
return s_num;
}
});
})(jQuery);
</script>
<script type="text/javascript">
(function(){
// $("#abc").abc();
// alert($.changeTwoDecimal(3.1415926));
// alert($.changeTwoDecimal(100 / 3));
// alert($.changeTwoDecimal(100 / 2));
/* alert($.changeTwoDecimal_f(3.1415926));
alert($.changeTwoDecimal_f(100 / 3));
alert($.changeTwoDecimal_f(100 / 2));*/
//这是最简单的方法了
var num = 3.146;//100 /2 ;//100/3;
alert(num.toFixed(2));
})();
</script>
</head>
<body>
<div id="abc"></div>
</body>
</html>本文出自 “我的JAVA世界” 博客,请务必保留此出处http://hanchaohan.blog.51cto.com/2996417/1629740
原文地址:http://hanchaohan.blog.51cto.com/2996417/1629740