I'm looking to get the length of a number in JavaScript or jQuery?
I've tried value.length without any success, do I need to convert this to a string first?
17 Answers
var x = 1234567; x.toString().length; This process will also work forFloat Number and for Exponential number also.
Ok, so many answers, but this is a pure math one, just for the fun or for remembering that Math is Important:
var len = Math.ceil(Math.log(num + 1) / Math.LN10); This actually gives the "length" of the number even if it's in exponential form. num is supposed to be a non negative integer here: if it's negative, take its absolute value and adjust the sign afterwards.
Update for ES2015
Now that Math.log10 is a thing, you can simply write
const len = Math.ceil(Math.log10(num + 1)); 12Could also use a template string:
const num = 123456 `${num}`.length // 6 1You have to make the number to string in order to take length
var num = 123; alert((num + "").length); or
alert(num.toString().length); 1I've been using this functionality in node.js, this is my fastest implementation so far:
var nLength = function(n) { return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1; } It should handle positive and negative integers (also in exponential form) and should return the length of integer part in floats.
The following reference should provide some insight into the method: Weisstein, Eric W. "Number Length." From MathWorld--A Wolfram Web Resource.
I believe that some bitwise operation can replace the Math.abs, but jsperf shows that Math.abs works just fine in the majority of js engines.
Update: As noted in the comments, this solution has some issues :(
Update2 (workaround) : I believe that at some point precision issues kick in and the Math.log(...)*0.434... just behaves unexpectedly. However, if Internet Explorer or Mobile devices are not your cup of tea, you can replace this operation with the Math.log10 function. In Node.js I wrote a quick basic test with the function nLength = (n) => 1 + Math.log10(Math.abs(n) + 1) | 0; and with Math.log10 it worked as expected. Please note that Math.log10 is not universally supported.
You should go for the simplest one (stringLength), readability always beats speed. But if you care about speed here are some below.
Three different methods all with varying speed.
// 34ms let weissteinLength = function(n) { return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1; } // 350ms let stringLength = function(n) { return n.toString().length; } // 58ms let mathLength = function(n) { return Math.ceil(Math.log(n + 1) / Math.LN10); } // Simple tests below if you care about performance. let iterations = 1000000; let maxSize = 10000; // ------ Weisstein length. console.log("Starting weissteinLength length."); let startTime = Date.now(); for (let index = 0; index < iterations; index++) { weissteinLength(Math.random() * maxSize); } console.log("Ended weissteinLength length. Took : " + (Date.now() - startTime ) + "ms"); // ------- String length slowest. console.log("Starting string length."); startTime = Date.now(); for (let index = 0; index < iterations; index++) { stringLength(Math.random() * maxSize); } console.log("Ended string length. Took : " + (Date.now() - startTime ) + "ms"); // ------- Math length. console.log("Starting math length."); startTime = Date.now(); for (let index = 0; index < iterations; index++) { mathLength(Math.random() * maxSize); } 2There are three way to do it.
var num = 123; alert(num.toString().length); better performance one (best performance in ie11)
var num = 123; alert((num + '').length); Math (best performance in Chrome, firefox but slowest in ie11)
var num = 123 alert(Math.floor( Math.log(num) / Math.LN10 ) + 1) 0First convert it to a string:
var mynumber = 123; alert((""+mynumber).length); Adding an empty string to it will implicitly cause mynumber to turn into a string.
Well without converting the integer to a string you could make a funky loop:
var number = 20000; var length = 0; for(i = number; i > 1; ++i){ ++length; i = Math.floor(i/10); } alert(length); 2I got asked a similar question in a test.
Find a number's length without converting to string
const numbers = [1, 10, 100, 12, 123, -1, -10, -100, -12, -123, 0, -0] const numberLength = number => { let length = 0 let n = Math.abs(number) do { n /= 10 length++ } while (n >= 1) return length } console.log(numbers.map(numberLength)) // [ 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 1 ] Negative numbers were added to complicate it a little more, hence the Math.abs().
A way for integers or for length of the integer part without banal converting to string:
var num = 9999999999; // your number if (num < 0) num = -num; // this string for negative numbers var length = 1; while (num >= 10) { num /= 10; length++; } alert(length); 2I would like to correct the @Neal answer which was pretty good for integers, but the number 1 would return a length of 0 in the previous case.
function Longueur(numberlen) { var length = 0, i; //define `i` with `var` as not to clutter the global scope numberlen = parseInt(numberlen); for(i = numberlen; i >= 1; i) { ++length; i = Math.floor(i/10); } return length; } As now we have a template literal, can also write it as:
let a = 123 console.log(`${a}`.length) // 3 I'm perplex about converting into a string the given number because such an algorithm won't be robust and will be prone to errors: it will show all its limitations especially in case it has to evaluate very long numbers. In fact before converting the long number into a string it will "collapse" into its exponential notation equivalent (example: 1.2345e4). This notation will be converted into a string and this resulting string will be evaluated for returning its length. All of this will give a wrong result. So I suggest not to use that approach.
Have a look at the following code and run the code snippet to compare the different behaviors:
let num = 116234567891011121415113441236542134465236441625344625344625623456723423523429798771121411511034412365421344652364416253446253446254461253446221314623879235441623683749283441136232514654296853446323214617456789101112141511344122354416236837492834411362325146542968534463232146172368374928344113623251465429685; let lenFromMath; let lenFromString; // The suggested way: lenFromMath = Math.ceil(Math.log10(num + 1)); // this works in fact returns 309 // The discouraged way: lenFromString = String(num).split("").length; // this doesn't work in fact returns 23 /*It is also possible to modify the prototype of the primitive "Number" (but some programmer might suggest this is not a good practice). But this is will also work:*/ Number.prototype.lenght = () => {return Math.ceil(Math.log10(num + 1));} lenFromPrototype = num.lenght(); console.log({lenFromMath, lenFromPrototype, lenFromString});Try this:
$("#element").text().length; 0Yes you need to convert to string in order to find the length.For example
var x=100;// type of x is number var x=100+"";// now the type of x is string document.write(x.length);//which would output 3. 0To get the number of relevant digits (if the leading decimal part is 0 then the whole part has a length of 0) of any number separated by whole part and decimal part I use:
function getNumberLength(x) { let numberText = x.toString(); let exp = 0; if (numberText.includes('e')) { const [coefficient, base] = numberText.split('e'); exp = parseInt(base, 10); numberText = coefficient; } const [whole, decimal] = numberText.split('.'); const wholeLength = whole === '0' ? 0 : whole.length; const decimalLength = decimal ? decimal.length : 0; return { whole: wholeLength > -exp ? wholeLength + exp : 0, decimal: decimalLength > exp ? decimalLength - exp : 0, }; }