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

2022-01-17 00:00:00 string decimal numbers javascript

我有一组带小数的字符串数字,例如:23.4569.450123.01...我需要检索每个数字的小数位数,知道它们至少有 1 个小数.

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

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

在这种情况下,尾随零确实算作小数,这与 相关问题.

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

解决方案

function decimalPlaces(num) {var match = (''+num).match(/(?:.(d+))?(?:[eE]([+-]?d+))?$/);if (!match) { 返回 0;}返回数学.max(0,//小数点右边的位数.(匹配[1]?匹配[1].长度:0)//调整科学记数法.- (match[2] ? +match[2] : 0));}

额外的复杂性是处理科学记数法

<块引用>

decimalPlaces('.05')2小数位('.5')1小数位('1')0小数位('25e-100')100小数位('2.5e-99')100小数位('.5e1')0小数位('.25e1')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 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.

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

相关文章