LavsTo
LavsTo

Reputation: 129

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. i.e 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
  }

});

Upvotes: 1

Views: 774

Answers (2)

ferhado
ferhado

Reputation: 2594

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));

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55740

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>

Upvotes: 2

Related Questions