0

I have this;

export const countDecimals = (value) => {
  let num = parseFloat(value.replace(/,/g, ""));
  if (Math.floor(num) === num) return 0;
  return num.toString().split(".")[1].length || 0;
}

it works until I enter a number with trailing zero, such as 2.10. It ignores the zero and returns 1.

How to fix this?

P.S. Reason I am doing parseFloat is because in my case value is string and will be formatted if it is a large number like "2,190.10".

Aaron
  • 35
  • 5

3 Answers3

0

You can do something like this:

export const countDecimals = (value) => {
  //Value is string type
  const num = value.split('.') //Split the int and the decimal
  return num[1] ? num[1].length : 0
  //Return the number of decimals after the dot or 0 if there are no decimals
}
  /*
  I.e if value is 2.10 num will be equal to ['2','10'] num[1] is the 
  decimal part
  */
Juan Rambal
  • 573
  • 2
  • 6
0

const countDecimals = (value) => {
  const num = value.toString().replace(/,/g, '');
  if (!num.includes('.')) return 0
  return num.toString().split(".")[1].length; 
}

console.log(countDecimals("2,000,222.2200"));
console.log(countDecimals("2"));
console.log(countDecimals("2.1"));
console.log(countDecimals("2.10"));
console.log(countDecimals(2));
console.log(countDecimals(2.1));
-1

try this

  const countDecimals = value => {
    const num = +value;
    if (Math.floor(num) === num) {
      return 0;
    }
    return value.split('.')[1].length;
  };
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Bogdan Pryvalov
  • 156
  • 1
  • 7
  • 1
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Apr 03 '21 at 08:04