Javascript:如何检索* * *号的小数位数? [英] Javascript: How to retrieve the number of decimals of a *string* number?
问题描述
我有一组带小数的字符串数字,例如: 23.456
, 9.450
, 123.01
...我需要检索每个数字的小数位数,知道它们至少有1个小数。
I have a set of string numbers having decimals, for example: 23.456
, 9.450
, 123.01
... I need to retrieve the number of decimals for each number, knowing that they have at least 1 decimal.
In换句话说, retr_dec()
方法应返回以下内容:
In other words, the retr_dec()
method should return the following:
retr_dec("23.456") -> 3
retr_dec("9.450") -> 3
retr_dec("123.01") -> 2
在这种情况下,尾随零计算为小数,与此相关问题。
Trailing zeros do count as a decimal in this case, unlike in this related question.
在Javascript中是否有一个简单/交付的方法来实现这一点,或者我应该计算小数点位置并计算字符串长度的差异?谢谢
Is there an easy/delivered method to achieve this in Javascript or should I compute the decimal point position and compute the difference with the string length? Thanks
推荐答案
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));
}
额外的复杂性是处理科学记数法所以
The extra complexity is to handle scientific notation so
decimalPlaces('.05')
2
decimalPlaces('.5')
1
decimalPlaces('1')
0
decimalPlaces('25e-100')
100
decimalPlaces('2.5e-99')
100
decimalPlaces('.5e1')
0
decimalPlaces('.25e1')
1
这篇关于Javascript:如何检索* * *号的小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!