简体   繁体   English

使用 Javascript 计算小数点前后的位数

[英]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.我有一个要求,我应该允许小数点前最多 14 位数字和小数点后最多 4 位数字。

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.有没有一种方法可以让用户知道他是否输入了 222222222222222.222 - 一旦他使用 Javascript 离开该文本框,小数点前 15 位将无效。

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:另外,上面的 function 给了我错误:

Object Expected.预计 Object。

Can anyone help me with this.谁能帮我这个。

Why not use the split() method (untested code below):为什么不使用split()方法(下面的未经测试的代码):

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):以下将采用任何数字并返回一个小数点前最多 14 位和之后最多 4 位的数字(实际上它并没有验证输入是一个数字,但你得到了图片):

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.我不是计算机科学家,但这是我在 JS 中拼凑起来的东西,可以在数学上做到这一点。 Supports negative numbers, scientific notation, and can parse a value as large as 10^308 and as small as 10^-323.支持负数、科学计数法,可以解析大到 10^308 小到 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 let digitsBefore = Math.ceil(Math.log10(Math.floor(Math.abs(x))+1))其中 x 是数字
  2. The total string length should not exceed digitsBefore+1+4 .总字符串长度不应超过digitsBefore+1+4 The +1 is for the decimal point, the four is the number of decimals you allow. +1 是小数点,四是您允许的小数位数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM