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)
更复杂的是处理科学记数法
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
Jac*_*ack 57
function retr_dec(num) {
return (num.split('.')[1] || []).length;
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*ock 11
function retr_dec(numStr) {
var pieces = numStr.split(".");
return pieces[1].length;
}
Run Code Online (Sandbox Code Playgroud)
由于还没有基于正则表达式的答案:
/\d*$/.exec(strNum)[0].length
Run Code Online (Sandbox Code Playgroud)
请注意,这对于整数“失败”,但根据问题规范,它们永远不会发生。
| 归档时间: |
|
| 查看次数: |
57992 次 |
| 最近记录: |