Friday 6 October 2017

Regular expression to filter the float value with minimum maximum length before and after the decimal

The below javascript example shows whether the given input has float value with limited length numbers before (min 2 to max 5) and after (2) the decimal point .

The Regix is : /^([0-9]{2,5}\.?[0-9]{2})$/
 
function isFloat(input)
{
  var regxExp = /^([0-9]{2,5}\.?[0-9]{2})$/
 var result = input.search(regxExp);
  console.log('Is '+ input + ' valid float number: ', result);
  
  return (result < -1) ? true : false;
}

var input = '312g37.78';
var result = isFloat(input);
console.log('Is '+ input + ' valid float number: ', result);

// Output (FALSE due to invalid letter)
Is "312s37.78" valid float number:  false

var input = '312327.782';
var result = isFloat(input);
console.log('Is '+ input + ' valid float number: ', result);

// Output: (FALSE due to invalid length)
Is "312327.782" valid float number:  false

var input = '3.78';
var result = isFloat(input);
console.log('Is "'+ input + '" valid float number: ', result);
// Output: (FALSE due to invalid length which is less than two (before the decimal point))
Is "3.78" valid float number:  false

var input = '31237.78';
var result = isFloat(input);
console.log('Is '+ input + ' valid float number: ', result);
// Output
Is "31237.78" valid float number:  true

var input = '317.78';
var result = isFloat(input);
console.log('Is "'+ input + '" valid float number: ', result);
// Output
Is "317.78" valid float number:  true




No comments:

Post a Comment

Please post any queries and comments here.