Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

allowing input only for float number

I have pain-time when making input that only allows float number with jquery library. my code can't prevent chacacter "." when it's becoming first input, can anyone guide me to solve this problem?

$('.filterme').keypress(function(eve) {
   if (    ( eve.which != 46 || $(this).val().indexOf('.') != -1 ) 
        && ( eve.which <  48 || eve.which > 57 ) 
        || ( $(this).val().indexOf('.') == 0) 
      )
   {
       eve.preventDefault();
   }
});​
like image 240
moc4yu Avatar asked Apr 14 '12 04:04

moc4yu


People also ask

How do I allow only float inputs in Python?

To take a float user input: Use the input() function to take input from the user. Use a try/except statement to make sure the input value is a float. Use the float() class to convert the string to a float.

How do you input a number as a float?

How to take input as a float? There is no such method, that can be used to take input as a float directly – but input string can be converted into a float by using float() function which accepts a string or a number and returns a float value.

Does input type number allow float?

For any floating-point numbers, use type="number”, as it is widely supported and can also help to prevent random input.

Can float store numbers?

float and double both have varying capacities when it comes to the number of decimal digits they can hold. float can hold up to 7 decimal digits accurately while double can hold up to 15. Let's see some examples to demonstrate this.


1 Answers

I use this - works for keyboard input or copy and paste

$('input.float').on('input', function() {
  this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="text" class="float" />

Explanation:

  • First regex replaces anything that's not a number or a decimal.
  • Second regex removes any instance of a second decimal.
like image 55
Eaten by a Grue Avatar answered Sep 21 '22 04:09

Eaten by a Grue