1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
<!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>
|
本文转自韩立伟 51CTO博客,原文链接:http://blog.51cto.com/hanchaohan/1629740
,如需转载请自行联系原作者