Javascript: How to retrieve the number of decimals of a *string* number?

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


Solution 1:

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

Solution 2:

function retr_dec(num) {
  return (num.split('.')[1] || []).length;
}

Solution 3:

function retr_dec(numStr) {
    var pieces = numStr.split(".");
    return pieces[1].length;
}

Solution 4:

Since there is not already a regex-based answer:

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

Note that this "fails" for integers, but per the problem specification they will never occur.

Solution 5:

You could get the length of the decimal part of your number this way:

var value = 192.123123;
stringValue = value.toString();
length = stringValue.split('.')[1].length;

It makes the number a string, splits the string in two (at the decimal point) and returns the length of the second element of the array returned by the split operation and stores it in the 'length' variable.