开发者

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

开发者 https://www.devze.com 2023-03-28 00:29 出处:网络
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.

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("onk开发者_开发百科eyup", "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.


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.)


Use a regular expression

summat like

pattern = /^\d{1,14)(\.{1,4}\)?$/;

if (patten.test(yourNumber)) {
// Hunky dory
}
else
{
// have another bash
}


I think we can agree that converting numbers into strings and counting the digits left of the decimal is gross, especially considering that very large numbers can get converted to scientific notation.

I am not a computer scientist but here is something I cobbled together in JS that will do this mathematically. Supports negative numbers, scientific notation, and can parse a value as large as 10^308 and as small as 10^-323.

function countDigits(value) {
  if (value === 0) return { wholePlaces: 0, decimalPlaces: 0 };

  var absValue = Math.abs(value); // -15.555 becomes 15.555
  var wholePlaces = 0;
  for (; wholePlaces <= 308; ++wholePlaces) { // Number.MAX_VALUE is 1.798e+308
    if (absValue < Math.pow(10, wholePlaces))
      break;
  }

  var decimalValue = absValue - Math.floor(absValue); // 15.555 - 15 = 0.555
  var decimalPlaces = 0;
  for (; decimalPlaces >= -323; --decimalPlaces) { // Number.MIN_VALUE is 5e-324
    var temp = (decimalValue / Math.pow(10, decimalPlaces)) + 0.09; // Adding 0.09 to counter float errors
    if (temp - Math.floor(temp) < 0.1)  // If the decimal remaining is smaller that 0.1, we've reached the end
      break;
  }
  decimalPlaces = Math.abs(decimalPlaces);
  return {
    wholePlaces,
    decimalPlaces,
  }
}

countDigits(0);         // { wholePlaces: 0, decimalPlaces: 0 }
countDigits(0.10);      // { wholePlaces: 0, decimalPlaces: 1 }
countDigits(-0.10);     // { wholePlaces: 0, decimalPlaces: 1 }
countDigits(0.10000);   // { wholePlaces: 0, decimalPlaces: 1 }
countDigits(-0.10000);  // { wholePlaces: 0, decimalPlaces: 1 }
countDigits(5);         // { wholePlaces: 1, decimalPlaces: 0 }
countDigits(-5);        // { wholePlaces: 1, decimalPlaces: 0 }
countDigits(15.555);    // { wholePlaces: 2, decimalPlaces: 3 }
countDigits(-15.555);   // { wholePlaces: 2, decimalPlaces: 3 }
countDigits(215.555);   // { wholePlaces: 3, decimalPlaces: 3 }
countDigits(-215.555);  // { wholePlaces: 3, decimalPlaces: 3 }
countDigits(1.55555e+4) // { wholePlaces: 5, decimalPlaces: 1 } (15555.5)


Another option via math

  1. You can get the digits of the number-part before the comma via the following line
    let digitsBefore = Math.ceil(Math.log10(Math.floor(Math.abs(x))+1)) where x is the number
  2. The total string length should not exceed digitsBefore+1+4. The +1 is for the decimal point, the four is the number of decimals you allow.
0

精彩评论

暂无评论...
验证码 换一张
取 消