The easiest way to get the number of decimal places in a number in JavaScript

Is there a better way to determine the number of decimal places per number than in my example?

var nbr = 37.435.45; var decimals = (nbr!=Math.floor(nbr))?(nbr.toString()).split('.')[1].length:0; 

For the better, I mean speeding up execution and / or using the built-in JavaScript function, i.e. something like nbr.getDecimals ().

Thanks in advance!

EDIT:

After modifying the answer of series0ne, the fastest way I could handle it is:

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

Speed ​​Test: http://jsperf.com/checkdecimals

+6
source share
3 answers
 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(); // 9 

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; } 
+22
source

Adding an answer to serial0ne, if you want the code not to give an error for an integer and get the result 0 when there are no decimal places, use this:

 var countDecimals = function (value) { if ((value % 1) != 0) return value.toString().split(".")[1].length; return 0; }; 
+8
source

Regex are very inefficient in calculations, they are average, if you can go the other way. Therefore, I would avoid them :)

Things like "Number% 1" return a rounded decimal value (2.3% 1 = 0.2999999999999998), and in the general case, I would advise you to use strings as early as possible, since approximations with real numbers can change the number of decimal places.

So, yours is fine, but I will look for a way to optimize it.

Edit:

 function CountDecimalDigits(number) { var char_array = number.toString().split(""); // split every single char var not_decimal = char_array.lastIndexOf("."); return (not_decimal<0)?0:char_array.length - not_decimal; } 
0
source

Source: https://habr.com/ru/post/948336/


All Articles