Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to parseInt a number that start with 0?

I have this string: '044600171940'.
I want to parse the string to a number with parseInt, but the value returns a number without the 0 in the front.

Is it possible to return the number with a leading 0 (e.g. 044600171940)?

var arr = ['044600171941','044600171940'];

var last = arr[arr.length -1];
var number = parseInt(last)
console.log(number)//44600171940

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

padStart(int, character) fills up the start of a string until the length is int characters long.

var arr = ['044600171941','044600171940'];

var last = arr[arr.length -1];

const addToNumberString = (intStr, value) => {
  let originalLength = intStr.length
  let sumInt = Number(intStr) + value;
  let sumIntStr = String(sumInt);

  return sumIntStr.padStart(originalLength, '0');
};

console.log(addToNumberString(last, 1)) // '044600171941'

…and here is a solution based off the fact that the value is always 12 characters long.

const numberLength = 12;

const addPadding = (number) => {
  return String(number).padStart(numberLength, 0);
};

var arr = ['044600171941','044600171940'];

var last = arr[arr.length -1];
var number = parseInt(last)

console.log( addPadding(17) )         // '000000000017'

console.log( addPadding(number) )     // '044600171940'

console.log( addPadding(number + 1) ) // '044600171941'
1 comments

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading