1. 程式人生 > >javascript-zero-保留2位小數

javascript-zero-保留2位小數

BE ntb script his ret char tostring str2 num

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>format-number</title>
 6 </head>
 7 <body>
 8     <input type="text" id="input"><input type="text" id="output">
 9 </body>
10 <script>
11 var
ipt=document.getElementById(input); 12 var opt=document.getElementById(output); 13 ipt.oninput=function(){ 14 opt.value=zero(this.value); 15 } 16 function zero(num){ 17 var str=num.toString(); 18 if(str.indexOf(".")==-1){ 19 return num+".00"; 20 }else{ 21 var len=str.indexOf(
"."); 22 if(str.slice(str.indexOf(.)).length == 2){ 23 return num+"0" 24 }else if(str.slice(str.indexOf(.)).length > 3){ 25 var len=str.indexOf("."); 26 var str1=str.slice(0,len); 27 var leng=str1.length+3; 28 var str2=
str.slice(0,leng); 29 return Number(str2); 30 }else{ 31 return num; 32 } 33 } 34 } 35 </script> 36 </html>

javascript-zero-保留2位小數