Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count the number of digits before and after decimal places using Javascript

I have a requirement where I should allow a maximum of 14 digits before decimal place and a maximum of 4 digits after decimal place.

Is there a way that I can let the user know if he is entering 222222222222222.222 -- 15 digits before decimal is invalid once he is out of that textbox using Javascript.

I tried this but it did not help me:

  MynewTextBox.Attributes.Add("onkeyup", "javascript:this.value=Comma(this.value);");

function Comma( Num ) {

  var period = Num.indexOf('.'); 
   if ( Num.length > (period + 4)) 
   alert("too many after decimal point");
   if ( period != -1 ) 
   {
      Num += '00000'; 
      Num = Num.substr( 0, (period + 4));
   } 

Also, the above function is giving me the error:

Object Expected.

Can anyone help me with this.

like image 614
Janet Avatar asked Dec 17 '22 10:12

Janet


1 Answers

Why not use the split() method (untested code below):

function Comma(num) {
  var s = num.split('.');
  if (s[0].length > 14) {
    // Too many numbers before decimal.
  }
  if (s[1].length > 4) {
    // Too many numbers after decimal.
  }
}

Edit
The following will take any number and return a number with at most 14 digits before the decimal point and at most 4 digits after (well it doesn't actually verify that the input is a number but you get the picture):

function Comma(num) {
  var s = num.split('.');
  var beforeDecimal = s[0];         // This is the number BEFORE the decimal.
  var afterDecimal = '0000';        // Default value for digits after decimal
  if (s.length > 1)                 // Check that there indeed is a decimal separator.
    afterDecimal = s[1];            // This is the number AFTER the decimal.
  if (beforeDecimal.length > 14) {
    // Too many numbers before decimal.
    // Get the first 14 digits and discard the rest.
    beforeDecimal = beforeDecimal.substring(0, 14);
  }
  if (afterDecimal.length > 4) {
    // Too many numbers after decimal.
    // Get the first 4 digits and discard the rest.
    afterDecimal = afterDecimal.substring(0, 4);
  }

  // Return the new number with at most 14 digits before the decimal
  // and at most 4 after.
  return beforeDecimal + "." + afterDecimal;
}

(And as always the code is untested.)

like image 86
Sani Singh Huttunen Avatar answered Jan 12 '23 00:01

Sani Singh Huttunen