简体   繁体   中英

Append values before and after decimal point Javascript

I have numeric fields on form were users can occasionally type a decimal value with decimal place but no values on one side. ie the intended value to be entered can be 5 or 5.00 but occasionally a user can type .5 OR 5. so in this case if they have left out values before the decimal place, I would like to add/append the value with 0.5 or if they have left out the values after the decimal place I would like to add/append with 5.00

.5 => 0.5
5. => 5.00

Ideally the input value would then be updated onBlur or when user clicks/tabs away from that field or anywhere else on the page. My quick attempt at this is currently as follows (untested)

$('input').on('blur', function () {

  var currentValue = $(this).val();

  var splitNumber = currentValue.split('.');
  var beforeDecimal = splitNumber[0];
  var afterDecimal = splitNumber[1];

  if (beforeDecimal.length < 1)
  {
    //add one zero before decimal
  }

  if (afterDecimal.length < 1)
  {
    //add two zeros after decimal
  }

});

Instead you can just use a combination of parseFloat and toFixed

parseFloat('.5') --> 0.5
parseFloat('5.') --> 5

 $('input').on('blur', function() { let value = this.value; if(!isNaN(value)) { let parsedValue = parseFloat(value); $('.output').text(parsedValue.toFixed(2)); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <input type="text" /> <span>Output: </span> <span class="output"> </span> 

Here is an example may help you:

  var myNum1 = .5; var myNum2 = 5.; function pad(num){ return num.toFixed(2); } console.log(pad(myNum1)); console.log(pad(myNum2)); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM