简体   繁体   中英

issue with counting digits of a number

Here is a code to count the digits of a given number.

There are two issues with this code that I can't fix without a hand:

First : If we have the function like count(502.1000); the output for decimals would be 1 instead of 4 ...

Second : If we have a number without decimals like count(5024); the output for numbers would be 1 instead of 4 ...

Here is the code:

 count(502.134); // Desired result is Numbers: 3 Decimals 3 count(502.1000); // Desired result is Numbers: 3 Decimals 4 count(5024); // Desired result is Numbers: 4 Decimals 0 function count(num) { Number.prototype.countDecimals = function () { if(Math.floor(this.valueOf()) === this.valueOf()) return 0; return this.toString().split(".")[1].length || 0; } Number.prototype.countNumber = function () { if(Math.floor(this.valueOf()) === this.valueOf()) return 1; return this.toString().split(".")[0].length || 0; } var a = Math.abs(num).countNumber(); var b = Math.abs(num).countDecimals(); console.log('Numbers: ' + a + ' Decimals '+ + b) }

Sorry, I thought it would be quicker to write my own function than analyse your code:

function getDigitLength(num) {
  if (!num) {
      return;
  }

  const numString = num.toString();
  const split = numString.split('.');

  const numbers = split[0].length;

  const decimals = split[1] ? split[1].length : 0;

  console.log('Numbers: ' + numbers + ' Decimals '+ decimals);
}

Made this really quick, some refactoring could be done. It should result in what you are after though.

By the way, for this count(502.1000); // Desired result is Numbers: 3 Decimals 4 count(502.1000); // Desired result is Numbers: 3 Decimals 4 is difficult because javascript will convert 502.1000 to 502.1 . Only if you pass 502.1000 as a string will it work.

Try this . But only way(as pr my knowledge) 502.1000 will give proper result if you can convert that to string, not sure if that is possible in your implementation.

 var count = function(value) {
        var deccnt = 0;
        var numcnt = 0;
        try {
        deccnt = value.toString().split(".")[1].length || 0;
        } catch(e){}
        try {
        numcnt = value.toString().split(".")[0].length || 0;
        } catch(e){}
        alert(numcnt + " : " + deccnt);
    }

var num1 = 502.134;
    count(num1.toString())
    num1 = "502.1000";
    count(num1);
    num1 = 5024;
    count(num1.toString())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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