price validation with decimal value

price validation with decimal value

by sanat gupta

HTML

<input type="text" id="price">

JavaScript

$(function(){
 var finalprice = '';
	 $('#price').on('change',function(){
      var value = $(this).val();
     
     if(value){
      var newval =  $(this).val(parseFloat(value).toFixed(2));  
      var finalval = newval[0].value; 
      var checkedNew = finalval.split('.');
       if(checkedNew[0] == 6 || checkedNew[1] > 00){
       		if(checkedNew[0].length >= 6 && checkedNew[1] > 00){
          	var lastindex = checkedNew[1].slice(-1);
            if(lastindex > 0){
              finalprice = checkedNew[0]+checkedNew[1]; 
            }else{
              finalprice = checkedNew[0]+lastindex; 
            }
          }else{
          	finalprice = checkedNew[0]; 
          }
       }else{
       		finalprice = checkedNew[0];
       }
      	
      if (finalprice.length > 6) {
   			 alert("length must be exactly 6 characters")
  		}
      console.log(finalprice);
    }else{
        $(this).val().empty();
    }
  });
});