1

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
  }

});
2
  • 1
    If you have a decimal point, you cannot split by comma. Commented Aug 14, 2018 at 22:10
  • yes you are right, that was a typo on my end. Commented Aug 14, 2018 at 22:18

2 Answers 2

2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Although you do risk introducing floating point rounding errors if there are a lot of decimal places.
@mpen That is always the case. It depends on the number of decimals OP wants it to round to
Not always. Input was a string. If you keep it as a string there's no need to introduce rounding error. But yes, this is an easy solution.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.