在项目中有时候会遇到要求输入的数字是整数或者小数点后绑定2位小数,因此可以用.toFixed(2)方法
下面是关于toFixed()方法的demo;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<input type=
"number"
value=
""
class
=
"inputVal"
>
<button
class
=
"inputs"
style=
"width: 50px;height: 20px;"
>
script中的代码:
<script src=
"https://cdn.bootcss.com/jquery/2.1.4/jquery.min.js"
></script>
<script>
$(function (){
// var num = 19.567.toFixed(2);//四舍五入,结果为19.57
$(
'.inputVal'
).keyup(function() {
var
coverNume = $(
'.inputVal'
).val();
console.log(coverNume);
var
sonm = Number(coverNume).toFixed(2);
//Number 把字符串转化为数字
console.log(sonm);
});
});
</script>
|
还有可以通过Math中的方法:
1
2
3
4
5
|
var
a = Math.floor(5.55);
//向下取整,结果为5
var
b = Math.ceil(5.223);
//向上取整,结果为6
var
c = Math.round(2.6);
//四舍五入,结果为3
var
d = Math.round(2.4);
//四舍五入,结果为2
console.log(b);
|