-1

Possible Duplicate:
Simple regular expression for a decimal with a precision of 2

HI i need to validate a number using regex. The main idea is that i have the integer part, the decimal part and the decimal separator of a number. For example if i have this:

var integer_part = 4;
var decimal_part = 2;
var decimal_separator = ".";

// will be valid numbers
// 2546.33 
// 12
// 1.33
// 263
// 0

can i make a regex string with the values in the variables to validate a string ¿?

Community
  • 1
  • 1
Ramiro Nava Castro
  • 197
  • 1
  • 4
  • 12

3 Answers3

3

You don't need a regex for this:

!isNaN(parseFloat(n)) && isFinite(n);

That checks a number is a float, isn't NaN and isn't infinity.

This sounds like an XY problem. What you should have asked is How can I validate a number? and left the regex part out.

Jivings
  • 21,712
  • 6
  • 52
  • 95
1

Though it is not clear from your question, I am assuming you want to use the variables to determine the range of allowable values in your regex If so, you can make your pattern string like this:

pattern = '/[\d]{0,' + integer_part + '}(' + decimal_separator + '[\d]{1,' + decimal_part + '})?/';

This is a basic implementation. In this case, in order to use . as you separator you would actually want to set decimal_separator = '\.'; This is to escape the decimal which is wildcard match in regex.

If you really want to look for more edge cases, you might want to build up your pattern conditionally like this:

pattern = '/[\d]{0,' + integer_part + '}';
if (decimal_part > 0) {
    if (decimal_separator == '.') {
        pattern += '(\.';
    } else {
        pattern +=  '(' + decimal_separator;
    }
    pattern += '[\d]';
    if (decimal_part == 1) {
         pattern += '{1}';
    } else {
         pattern += '{1,' + decimal_part + '}';
    }
    pattern += ')?';
}
pattern += '/';
Mike Brant
  • 66,858
  • 9
  • 86
  • 97
0

Just use this regex, it will look for anything with

\d+(\.\d+)

However, there might be a better way to do it.

Boolean isFloat=false;
try
{
   float num=parseFloat(n);
   isFloat=!isNaN(num) && isFinite(num);
}
catch (NumberFormatException ex)
{
   //Isn't a number
}
PearsonArtPhoto
  • 35,989
  • 16
  • 107
  • 136