简体   繁体   中英

how to get the number of digits in a number with leading zeros

For normal numbers, like var a = 123 , it is easy to count the number of digits (with a.toString().length ), but what if var a = 00123 ? (assume it is still in decimal).

There are a couple of problems you might experience here with a possible easy solution. First entering a number value with leading zeros, will be interpreted differently than expected. Generally it wont store the number in decimal format but instead octal or some other base. If you just want to get the length of that value then you need to store it as a string.

var a = '00123';
console.log(a.length);

Just keep in mind if you dont store it as a string the number will probably not be stored as decimal.

This is a common Javascript gotcha with a simple solution:

Just specify the base, or 'radix', like so:

parseInt('000123',10); // 123

You could also use Number:

Number('000123'); // 123

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM