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


<!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>


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM