保留小数点后两位,四舍五入与不四舍五入

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Document</title>
</head>

<body>
<input id="val" type="text">
<input id="btn" type="button" value="点击转换">
<script>
var btn = document.getElementById("btn");
btn.onclick=function(){
var val = document.getElementById('val').value;
var x = changeTwoDecimal_f(val);
console.log(x);
}
function changeTwoDecimal_f(x) {   
var f_x = parseFloat(x);     
var f_x = Math.floor(x * 100) / 100;   //不四舍五入
// var f_x = Math.round(x * 100) / 100;   //四舍五入
var s_x = f_x.toString();   
var pos_decimal = s_x.indexOf('.');   
if (pos_decimal < 0) {        pos_decimal = s_x.length;       
s_x += '.';    }   
while (s_x.length <= pos_decimal + 2) { s_x += '0'; }   
return s_x;
}
</script>
</body>

</html>

posted on 2017-10-10 11:12  萧皓灏博客园  阅读(3581)  评论(0编辑  收藏  举报

导航