Javascript : * string * 숫자의 소수 자릿수를 검색하는 방법은 무엇입니까?
나는 예를 들어, 소수를 가진 문자열 숫자의 집합이 : 23.456, 9.450, 123.01... 나는 그들이 적어도 1 소수점을 가지고 있음을 알고, 각 번호에 대한 소수의 번호를 검색 할 필요가있다.
즉, retr_dec()메서드는 다음을 반환해야합니다.
retr_dec("23.456") -> 3
retr_dec("9.450")  -> 3
retr_dec("123.01") -> 2
 
이 관련 질문 과 달리 후행 0은이 경우 10 진수로 계산됩니다 .
Javascript에서 이것을 달성하는 쉬운 / 전달 방법이 있습니까? 아니면 소수점 위치를 계산하고 문자열 길이와의 차이를 계산해야합니까? 감사
function decimalPlaces(num) {
  var match = (''+num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
  if (!match) { return 0; }
  return Math.max(
       0,
       // Number of digits right of decimal point.
       (match[1] ? match[1].length : 0)
       // Adjust for scientific notation.
       - (match[2] ? +match[2] : 0));
}
 
추가 복잡성은 과학적 표기법을 처리하는 것이므로
decimalPlaces('.05') 2 decimalPlaces('.5') 1 decimalPlaces('1') 0 decimalPlaces('25e-100') 100 decimalPlaces('2.5e-99') 100 decimalPlaces('.5e1') 0 decimalPlaces('.25e1') 1
function retr_dec(num) {
  return (num.split('.')[1] || []).length;
}
function retr_dec(numStr) {
    var pieces = numStr.split(".");
    return pieces[1].length;
}
정규식 기반 답변이 아직 없기 때문에 :
/\d*$/.exec(strNum)[0].length
 
정수에 대해서는 "실패"하지만 문제 사양에 따라 절대 발생하지 않습니다.
다음과 같이 숫자의 소수 부분 길이를 얻을 수 있습니다.
var value = 192.123123;
stringValue = value.toString();
length = stringValue.split('.')[1].length;
 
숫자를 문자열로 만들고 문자열을 소수점에서 둘로 분할하고 분할 연산에서 반환 된 배열의 두 번째 요소의 길이를 반환하고 'length'변수에 저장합니다.
String.prototype.match()와 함께 사용하여 일치하는 문자열을 RegExp /\..*/반환 하십시오..length-1
function retr_decs(args) {
  return /\./.test(args) && args.match(/\..*/)[0].length - 1 || "no decimal found"
}
console.log(
  retr_decs("23.456") // 3
  , retr_decs("9.450") // 3
  , retr_decs("123.01") // 2
  , retr_decs("123") // "no decimal found"
) 
 현재 허용되는 답변을 약간 수정하면 Number프로토 타입에 추가 되어 모든 숫자 변수가이 메서드를 실행할 수 있습니다.
if (!Number.prototype.getDecimals) {
    Number.prototype.getDecimals = function() {
        var num = this,
            match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
        if (!match)
            return 0;
        return Math.max(0, (match[1] ? match[1].length : 0) - (match[2] ? +match[2] : 0));
    }
}
 
다음과 같이 사용할 수 있습니다.
// Get a number's decimals.
var number = 1.235256;
console.debug(number + " has " + number.getDecimals() + " decimal places.");
// Get a number string's decimals.
var number = "634.2384023";
console.debug(number + " has " + parseFloat(number).getDecimals() + " decimal places.");
 
기존 코드를 사용하여 두 번째 경우도 다음 String과 같이 프로토 타입에 쉽게 추가 할 수 있습니다 .
if (!String.prototype.getDecimals) {
    String.prototype.getDecimals = function() {
        return parseFloat(this).getDecimals();
    }
}
 
다음과 같이 사용하십시오.
console.debug("45.2342".getDecimals());
A bit of a hybrid of two others on here but this worked for me. Outside cases in my code weren't handled by others here. However, I had removed the scientific decimal place counter. Which I would have loved at uni!
numberOfDecimalPlaces: function (number) {
    var match = ('' + number).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
    if (!match || match[0] == 0) {
        return 0;
    }
     return match[0].length;
}
I had to deal with very small numbers so I created a version that can handle numbers like 1e-7.
Number.prototype.getPrecision = function() {
  var v = this.valueOf();
  if (Math.floor(v) === v) return 0;
  var str = this.toString();
  var ep = str.split("e-");
  if (ep.length > 1) {
    var np = Number(ep[0]);
    return np.getPrecision() + Number(ep[1]);
  }
  var dp = str.split(".");
  if (dp.length > 1) {
    return dp[1].length;
  }
  return 0;
}
document.write("NaN => " + Number("NaN").getPrecision() + "<br>");
document.write("void => " + Number("").getPrecision() + "<br>");
document.write("12.1234 => " + Number("12.1234").getPrecision() + "<br>");
document.write("1212 => " + Number("1212").getPrecision() + "<br>");
document.write("0.0000001 => " + Number("0.0000001").getPrecision() + "<br>");
document.write("1.12e-23 => " + Number("1.12e-23").getPrecision() + "<br>");
document.write("1.12e8 => " + Number("1.12e8").getPrecision() + "<br>"); 
 Based on Liam Middleton's answer, here's what I did (without scientific notation):
numberOfDecimalPlaces = (number) => {
            let match = (number + "").match(/(?:\.(\d+))?$/);
            if (!match || !match[1]) {
                return 0;
            }
            return match[1].length;
        };
        
alert(numberOfDecimalPlaces(42.21)); 
 function decimalPlaces(n) {
  if (n === NaN || n === Infinity)
    return 0;
  n = ('' + n).split('.');
  if (n.length == 1) {
    if (Boolean(n[0].match(/e/g)))
      return ~~(n[0].split('e-'))[1];
    return 0;
  }
  n = n[1].split('e-');
  return n[0].length + ~~n[1];
}
ReferenceURL : https://stackoverflow.com/questions/10454518/javascript-how-to-retrieve-the-number-of-decimals-of-a-string-number
'Program Tip' 카테고리의 다른 글
| 디자인 패턴이 솔루션 대신 문제가되는 경우는 언제입니까? (0) | 2020.12.26 | 
|---|---|
| numpy의 배열에서 연속 요소 그룹을 찾는 방법은 무엇입니까? (0) | 2020.12.26 | 
| 문자열에서 숫자 추출-StringUtils Java (0) | 2020.12.26 | 
| Mongodb : 127.0.0.1:27017에 연결하지 못했습니다. 이유 : errno : 10061 (0) | 2020.12.26 | 
| 자바 수학에서 조합 'N choose R'? (0) | 2020.12.26 |