0

I need to split a string of numbers and convert to number. converted strings must not reduced or something. For example when i use to convert "01" in string to 01 in number like below, i got something wrong. For example i have this string "0601",

var _stringNumber = '0601';
var _number = Number('0601'); // result is 601

i need _number = 0601 but result is 601.

what is the solution?

12
  • 4
    You can't. Numbers ignores leading 0s. Commented Sep 15, 2017 at 18:59
  • 2
    Why do you think you need this? What is the use case? Commented Sep 15, 2017 at 19:00
  • 1
    It's the way numbers work since they discovered them centuries ago. Commented Sep 15, 2017 at 19:02
  • 2
    Then you just set the numbers, if it expects each property to actually be a number it is not going to expect a leading 0. Commented Sep 15, 2017 at 19:08
  • 1
    Classic XY Problem — you asked how to keep the leading zero but that was your own proposed solution to your real problem: how can you init your ngbCalendar. You should delete this question and ask a new one for what you are actually trying to do. Commented Sep 15, 2017 at 19:09

3 Answers 3

4

A number is a number; there is no way to distinguish 3 from 03 because these are the same number.

Sign up to request clarification or add additional context in comments.

Comments

0

You can use simple for loop

let stringNumber = '0601';
let tempNumbers = [];

for(let i = 0; i < stringNumber.length; i++) {
   tempNumbers.push(+stringNumber[i]);
}

let number = tempNumbers.join('');

// Result : 0601

Comments

-1

Make an Object

var MyNumber = function(stringNum) {
    var visualNumber = stringNum;
    var actualNumber = Number(visualNumber);
}

Usage:

var num = MyNumber('0601');
var dummyNum = 65;
var resultNum = dummyNum + num.actualNumber;
console.log(resultNum); // 666... (O.o) <- Oh noes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.