Javascript:如何检索***号的小数位数?

Jér*_*nge 56 javascript string numbers decimal

我有小数一组串数字,例如:23.456,9.450,123.01...我需要找回小数每个号码的数量,因为他们知道至少有1位小数.

换句话说,该retr_dec()方法应返回以下内容:

retr_dec("23.456") -> 3
retr_dec("9.450")  -> 3
retr_dec("123.01") -> 2
Run Code Online (Sandbox Code Playgroud)

在这种情况下,尾随零计数为小数,与此相关问题不同.

在Javascript中是否有一个简单/交付的方法来实现这一点,或者我应该计算小数点位置并计算字符串长度的差异?谢谢

Mik*_*uel 108

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));
}
Run Code Online (Sandbox Code Playgroud)

更复杂的是处理科学记数法

decimalPlaces('.05')
2
decimalPlaces('.5')
1
decimalPlaces('1')
0
decimalPlaces('25e-100')
100
decimalPlaces('2.5e-99')
100
decimalPlaces('.5e1')
0
decimalPlaces('.25e1')
1
Run Code Online (Sandbox Code Playgroud)

  • @arod,`decimalPlaces("1.00")=== 2`但是`decimalPlaces(1.00)=== 0`因为`(""+ 1.00)==="1"`.在功能上的数字,而不是原始的数字值的字符串表示,因为工作的原始数值没有固有的十进制 - [IEEE 854没能进的EcmaScript 5](http://intertwingly.net/blog/2008/07/11 /十进制合的ECMAScript). (2认同)

Jac*_*ack 57

function retr_dec(num) {
  return (num.split('.')[1] || []).length;
}
Run Code Online (Sandbox Code Playgroud)

  • @Deleteman感谢OP指定`知道他们至少有1个小数 (4认同)
  • 效果很好.如果在编辑之前字符串中没有小数引用此答案,则注释说不起作用. (3认同)

Dan*_*ock 11

function retr_dec(numStr) {
    var pieces = numStr.split(".");
    return pieces[1].length;
}
Run Code Online (Sandbox Code Playgroud)


Phr*_*ogz 5

由于还没有基于正则表达式的答案:

/\d*$/.exec(strNum)[0].length
Run Code Online (Sandbox Code Playgroud)

请注意,这对于整数“失败”,但根据问题规范,它们永远不会发生。

  • @LarryBattle 我感谢您的评论和全面性,但问题明确指出,_“知道他们至少有 1 位小数”_。如果你因为这个原因否决了我的正确答案,我请你重新考虑你的投票。 (5认同)