1. 程式人生 > >保留小數點後兩位,四舍五入與不四舍五入

保留小數點後兩位,四舍五入與不四舍五入

tex head change body func onclick set console click

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

保留小數點後兩位,四舍五入與不四舍五入