Simplest way of getting the number of decimals in a number in JavaScript [duplicate] Simplest way of getting the number of decimals in a number in JavaScript [duplicate] jquery jquery

Simplest way of getting the number of decimals in a number in JavaScript [duplicate]


Number.prototype.countDecimals = function () {    if(Math.floor(this.valueOf()) === this.valueOf()) return 0;    return this.toString().split(".")[1].length || 0; }

When bound to the prototype, this allows you to get the decimal count (countDecimals();) directly from a number variable.

E.G.

var x = 23.453453453;x.countDecimals(); // 9

It works by converting the number to a string, splitting at the . and returning the last part of the array, or 0 if the last part of the array is undefined (which will occur if there was no decimal point).

If you do not want to bind this to the prototype, you can just use this:

var countDecimals = function (value) {    if(Math.floor(value) === value) return 0;    return value.toString().split(".")[1].length || 0; }

EDIT by Black:

I have fixed the method, to also make it work with smaller numbers like 0.000000001

Number.prototype.countDecimals = function () {    if (Math.floor(this.valueOf()) === this.valueOf()) return 0;    var str = this.toString();    if (str.indexOf(".") !== -1 && str.indexOf("-") !== -1) {        return str.split("-")[1] || 0;    } else if (str.indexOf(".") !== -1) {        return str.split(".")[1].length || 0;    }    return str.split("-")[1] || 0;}var x = 23.453453453;console.log(x.countDecimals()); // 9var x = 0.0000000001;console.log(x.countDecimals()); // 10var x = 0.000000000000270;console.log(x.countDecimals()); // 13var x = 101;  // Integer numberconsole.log(x.countDecimals()); // 0