1 <!DOCTYPE HTML>2 <HTMLLang= "en">3 <Head>4 <MetaCharSet= "UTF-8">5 <title>Format-number</title>6 </Head>7 <Body>8 <inputtype= "text"ID= "Input"><inputtype= "text"ID= "Output">9 </Body>Ten <Script> One varIPT=document.getElementById ('input'); A varopt=document.getElementById ('Output'); - Ipt.oninput=function(){ - Opt.value=Zero ( This. value); the } - functionZero (num) { - varStr=num.tostring (); - if(Str.indexof (".")==-1){//integer + returnNum+". XX"; - }Else{ + varLen=Str.indexof ("."); A if(Str.slice (len). Length== 2){ //only 1 decimal places at returnNum+"0" - }Else if(Str.slice (len). Length> 3){//The number of decimal parts is greater than 2 bits - //Integer Part - varinteger=Str.slice (0, Len); - //the index value to be intercepted - varResindex=Integer.length+3; in //A string that retains two decimal places after being intercepted . - varResnumber=Str.slice (0, Resindex); to //two decimal places of the captured reserved + vardecimal=Str.slice (Len+1, Resindex); - if(Decimal=="xx"){ the returnNumber (Resnumber)+". XX"; * }Else{ $ //and turn it back into numbers .Panax Notoginseng returnNumber (resnumber); - } the }Else{//is a number with 2 decimal places. + returnnum; A } the } + } - </Script> $ </HTML>
1 console.log (zero)//11.002 console.log (zero (11.0))//11.00 3 console.log (zero (11.00))//11.004 console.log (zero (11.001))// 11.005 console.log (zero (11.1))//11.106 console.log ( Zero (11.00001))//11.00
javascript-reserved 2-bit decimal function method