programing

자바스크립트에서 숫자의 소수점 수를 구하는 가장 간단한 방법

telebox 2023. 10. 9. 22:28
반응형

자바스크립트에서 숫자의 소수점 수를 구하는 가장 간단한 방법

어떤 수에서 소수점의 수를 제 예제보다 더 잘 알아낼 수 있는 방법이 있을까요?

var nbr = 37.435.45;
var decimals = (nbr!=Math.floor(nbr))?(nbr.toString()).split('.')[1].length:0;

nbr.getDecimals()와 같은 네이티브 자바스크립트 함수를 더 빨리 실행하고/또는 사용하는 것이 좋습니다.

미리 감사드립니다!

편집:

series0ne 답변을 수정한 후 가장 빠른 방법은 다음과 같습니다.

var val = 37.435345;
var countDecimals = function(value) {
    if (Math.floor(value) !== value)
        return value.toString().split(".")[1].length || 0;
    return 0;
}
countDecimals(val);

속도 테스트: http://jsperf.com/checkdecimals

Number.prototype.countDecimals = function () {
    if(Math.floor(this.valueOf()) === this.valueOf()) return 0;
    return this.toString().split(".")[1].length || 0; 
}

프로토타입에 바인딩되면 십진 카운트를 얻을 수 있습니다 (countDecimals();숫자 변수에서 직접 추출합니다.

예.

var x = 23.453453453;
x.countDecimals(); // 9

숫자를 문자열로 변환하여 .에서 분할하고 배열의 마지막 부분을 반환하거나 배열의 마지막 부분이 정의되지 않은 경우(소수점이 없는 경우) 0을 반환하여 작동합니다.

프로토타입에 바인딩하지 않으려면 다음을 사용하면 됩니다.

var countDecimals = function (value) {
    if(Math.floor(value) === value) return 0;
    return value.toString().split(".")[1].length || 0; 
}

검정으로 편집:

저는 방법을 고쳤습니다. 또한 다음과 같이 작은 숫자로도 작동할 수 있도록 하기 위해서요.0.000000001

Number.prototype.countDecimals = function () {

    if (Math.floor(this.valueOf()) === this.valueOf()) return 0;

    var str = this.toString();
    if (str.indexOf(".") !== -1 && str.indexOf("-") !== -1) {
        return str.split("-")[1] || 0;
    } else if (str.indexOf(".") !== -1) {
        return str.split(".")[1].length || 0;
    }
    return str.split("-")[1] || 0;
}


var x = 23.453453453;
console.log(x.countDecimals()); // 9

var x = 0.0000000001;
console.log(x.countDecimals()); // 10

var x = 0.000000000000270;
console.log(x.countDecimals()); // 13

var x = 101;  // Integer number
console.log(x.countDecimals()); // 0

정수에 대한 오류를 발생시키지 않고 소수점이 없을 때 0의 결과를 얻도록 하려면 series0ne 답변에 다음을 추가합니다.

var countDecimals = function (value) { 
    if ((value % 1) != 0) 
        return value.toString().split(".")[1].length;  
    return 0;
};

정규 표현식은 계산에 매우 효율적이지 않습니다. 다른 방법으로 갈 수 있다면 비열합니다.그래서 저는 피하겠습니다 :)

"숫자 % 1"과 같은 경우에는 반올림한 십진수 값(2.3 % 1 = 0.299999999998)을 반환합니다. 일반적으로 실수의 근사치는 십진수의 수를 변경할 수 있으므로 가능한 한 빨리 문자열을 사용하는 것이 좋습니다.

그래서 당신 것은 괜찮지만, 최적화할 방법을 찾아보겠습니다.

편집:

function CountDecimalDigits(number)
{
  var char_array = number.toString().split(""); // split every single char
  var not_decimal = char_array.lastIndexOf(".");
  return (not_decimal<0)?0:char_array.length - not_decimal;
}

언급URL : https://stackoverflow.com/questions/17369098/simplest-way-of-getting-the-number-of-decimals-in-a-number-in-javascript

반응형