57

23.456たとえば、小数を含む文字列の数字のセットがあり9.450ます123.01

つまり、retr_dec()メソッドは次を返す必要があります。

retr_dec("23.456") -> 3
retr_dec("9.450")  -> 3
retr_dec("123.01") -> 2

この関連する質問とは異なり、この場合、末尾のゼロは小数としてカウントされます。

Javascriptでこれを達成するための簡単な/提供された方法はありますか、それとも小数点位置を計算して文字列の長さとの差を計算する必要がありますか? ありがとう

4

11 に答える 11

114
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
于 2012-05-04T18:53:36.993 に答える
59
function retr_dec(num) {
  return (num.split('.')[1] || []).length;
}
于 2012-05-04T18:51:12.510 に答える
10
function retr_dec(numStr) {
    var pieces = numStr.split(".");
    return pieces[1].length;
}
于 2012-05-04T18:53:14.170 に答える
5

まだ正規表現ベースの回答がないため:

/\d*$/.exec(strNum)[0].length

これは整数では「失敗」しますが、問題の仕様によれば、決して発生しないことに注意してください。

于 2012-05-04T18:52:45.683 に答える
2

String.prototype.match()withを使ってみて、一致した文字列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"
)

于 2016-01-13T15:36:16.900 に答える