Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

check for decimal point / places in text field 2

Status
Not open for further replies.

davejam

Technical User
Jan 6, 2004
313
GB
hi all,

managed to find some code on this but i just get errors when i try.

i have many text fields for numeric inputs within an ASP input screen.

On blur of each of these i run a check to make sure that the value entered is numeric.

Before it is submitted a calc runs to check that the 2 accounts balance.....

now i need to make sure i only allow 2 dp per text field.

had an idea (that i would use with vbscript) of checking the text field for a decimal '.', getting the place of it within the field, taking this off the length which would give me the trailing decimal places

if above 2 then error..... quite simple i thought, although i'm struggling with javascript, i seem to get so far then when searching for the '.' itself causes me issues.

also is trim a vbscript, javascript or vba function, can't remember, think i may need to utilise this also

cheers in advance for any help / suggestions

daveJam

*two wrongs don't make a right..... but three lefts do!!!!*
 
You can do a check like this:


Example number: 324.64
Code:
if (String(number).indexOf(".") < String(number).length - 3) {
alert("Number can only be 2 decimal places at most.";
return false;
}
In this example: String(number).indexOf(".") = 3
String(number).length - 3 = 3

Since 3 is not less than 3, it is valid.

This check will work on any number.

Note: It also allows for numbers like 34.5, which I would assume is ok.



[monkey][snake] <.
 
davejam, this is a function I use in my validation system.
It is setup to let you pass in the value to test and a minimum and maximum number of decimal places to test for.

The example monksnake gave will work but it does not test that you are actually dealing with a number, only that it has two places after the decimal.

The function below is flexible so that you can use it to test for any real number with a decimal, you can specify the number of decimal places, or you can set a range of decimal places allowing you to use the same function under different conditions.
To set for a fixed length of 2 you just set min and max both to 2.

Code:
function any_real_number_with_set_number_decimals(value,min,max) { 
  //Accepts number with decimal but it must have at least the min and at most the max places after the decimal
  var re = new RegExp("^-?\\d+\\.\\d{" + min + "," + max + "}?$");
  return re.test(value);
}

At my age I still learn something new every day, but I forget two others.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top