Programing

자바 스크립트에서 숫자의 길이

crosscheck 2020. 6. 28. 18:34
반응형

자바 스크립트에서 숫자의 길이


javascript / jquery에서 숫자의 길이를 얻으려고합니다.

나는 value.length아무런 성공없이 시도했지만 이것을 먼저 문자열로 변환해야합니까?


var x = 1234567;

x.toString().length;

이 프로세스는 또한 효과 Float NumberExponential number있습니다.


좋아, 많은 답변이 있지만 이것은 재미를 위해 또는 수학이 중요하다는 것을 기억하기위한 순수한 수학입니다.

var len = Math.ceil(Math.log(num + 1) / Math.LN10);

이것은 실제로 지수 형식 인 경우에도 숫자의 "길이"를 제공합니다. num음수가 아닌 경우, 음수가 아닌 경우 절대 값을 취한 후 부호를 조정하십시오.

ES2015 업데이트

이제는 Math.log10일입니다 . 간단히 쓸 수 있습니다.

const len = Math.ceil(Math.log10(num + 1));

길이를 얻으려면 숫자를 문자열로 만들어야합니다.

var num = 123;

alert((num + "").length);

또는

alert(num.toString().length);

node.js 에서이 기능을 사용 해왔으며 지금까지 가장 빠른 구현입니다.

var nLength = function(n) { 
    return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1; 
}

양수와 음수를 지수 형식으로 처리해야하며 정수 부분의 길이를 부동 수로 반환해야합니다.

다음 참조는이 방법에 대한 통찰력을 제공해야합니다. Weisstein, Eric W. "Number Length." MathWorld--Wolfram 웹 리소스에서.

비트 비트 연산이 Math.abs를 대체 할 수 있다고 생각하지만 jsperf는 Math.abs가 대다수의 js 엔진에서 제대로 작동한다는 것을 보여줍니다.

업데이트 : 의견에서 언급 했듯이이 솔루션에는 몇 가지 문제가 있습니다.

Update2 (해결 방법) : 어느 시점에서 정밀도 문제가 발생하고 Math.log(...)*0.434...예상치 못한 동작이 발생한다고 생각합니다 . 그러나 Internet Explorer 또는 모바일 장치가 차 한잔이 아닌 경우이 작업을 Math.log10기능으로 대체 할 수 있습니다 . Node.js에서 함수 nLength = (n) => 1 + Math.log10(Math.abs(n) + 1) | 0;를 사용 Math.log10하여 예상대로 작동 하는 빠른 기본 테스트를 작성 했습니다. 주의하시기 바랍니다 Math.log10보편적으로 지원되지 않습니다.


정수를 문자열로 변환하지 않으면 펑키 루프를 만들 수 있습니다.

var number = 20000;
var length = 0;
for(i = number; i > 1; ++i){
     ++length;
     i = Math.floor(i/10);
}

alert(length);​

데모 : http://jsfiddle.net/maniator/G8tQE/


먼저 문자열로 변환하십시오.

var mynumber = 123;
alert((""+mynumber).length);

빈 문자열을 추가하면 암시 적 mynumber으로 문자열로 바뀝니다.


세 가지 방법이 있습니다.

var num = 123;
alert(num.toString().length);

더 나은 성능 하나 (ie11에서 최고의 성능)

var num = 123;
alert((num + '').length);

수학 (Chrome, 파이어 폭스에서 최고의 성능이지만 IE11에서는 가장 느림)

var num = 123
alert(Math.floor( Math.log(num) / Math.LN10 ) + 1)

there is a jspref here http://jsperf.com/fastest-way-to-get-the-first-in-a-number/2


Could also use a template string:

const num = 123456
`${num}`.length // 6

I would like to correct the @Neal answer which was pretty good for integers, but the number 1 would return a length of 0 in the previous case.

function Longueur(numberlen)
{
    var length = 0, i; //define `i` with `var` as not to clutter the global scope
    numberlen = parseInt(numberlen);
    for(i = numberlen; i >= 1; i)
    {
        ++length;
        i = Math.floor(i/10);
    }
    return length;
}

Three different methods all with varrying speed.

// 34ms
let weissteinLength = function(n) { 
    return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1;
}

// 350ms
let stringLength = function(n) {
    return n.toString().length;
}

// 58ms
let mathLength = function(n) {
    return Math.ceil(Math.log(n + 1) / Math.LN10);
}

// Simple tests below if you care about performance.

let iterations = 1000000;
let maxSize = 10000;

// ------ Weisstein length.

console.log("Starting weissteinLength length.");
let startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    weissteinLength(Math.random() * maxSize);
}

console.log("Ended weissteinLength length. Took : " + (Date.now() - startTime ) + "ms");


// ------- String length slowest.

console.log("Starting string length.");
startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    stringLength(Math.random() * maxSize);
}

console.log("Ended string length. Took : " + (Date.now() - startTime ) + "ms");


// ------- Math length.

console.log("Starting math length.");
startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    mathLength(Math.random() * maxSize);
}

Try this:

$("#element").text().length;

Example of it in use


Yes you need to convert to string in order to find the length.For example

var x=100;// type of x is number
var x=100+"";// now the type of x is string
document.write(x.length);//which would output 3.

I got asked a similar question in a test.

Find a number's length without converting to string

const numbers = [1, 10, 100, 12, 123, -1, -10, -100, -12, -123, 0, -0]

const numberLength = number => {

  let length = 0
  let n = Math.abs(number)

  do {
    n /=  10
    length++
  } while (n >= 1)

  return length
}

console.log(numbers.map(numberLength)) // [ 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 1 ]

Negative numbers were added to complicate it a little more, hence the Math.abs().

참고URL : https://stackoverflow.com/questions/10952615/length-of-number-in-javascript

반응형