Number.prototype.countDecimals = function () { if(Math.floor(this.valueOf()) === this.valueOf()) return 0; return this.toString().split(".")[1].length || 0; }
When binding to a prototype, this allows you to get a decimal number ( countDecimals(); ) directly from a numeric variable.
eg.
var x = 23.453453453; x.countDecimals();
It works by converting a number to a string, splitting on . and returning the last part of the array, or 0 if the last part of the array is undefined (what would happen if there was no decimal point).
If you do not want to associate this with a prototype, you can simply use this:
var countDecimals = function (value) { if(Math.floor(value) === value) return 0; return value.toString().split(".")[1].length || 0; }
source share