1

I'm making a function that takes in user input and must display it as 7 characters i.e. if 42.54 was entered it would display 0004254. My issue is that I'm taking an integer and applying it to an array causing an undefined error when applying the 0's

function BackDataDefaultInput() {
// Balance
    var count;
    var newNum = "";
    var balanceText = document.getElementById('balanceNumBox').value;
    count = balanceText.length;

while (count > 0 && count < 7) {
    newNum += '0';
    count++
}
var formattedBalance = parseInt(balanceText, 10) * 100;
for (var i = 0; i < balanceText.length; i++) {
    formattedBalance[i] = new Array();
    // Error here showing as undefined for formattedBalance[i]
     newNum += formattedBalance[i];
}

This code worked before I had to multiply it by 100 to get the right format. as I was just appending two strings. Can somebody help me think of a solution?

3 Answers 3

2

Primitives (like numbers) are immutable; if you have

var formattedBalance = parseInt(balanceText, 10) * 100;

you can't proceed to reassign index properties like

formattedBalance[i] = new Array();

It would probably be easier to remove the (possible) period with a regex and use padStart rather than mess with arrays:

function BackDataDefaultInput() {
  const balanceText = '42.54'; // document.getElementById('balanceNumBox').value;
  console.log(
    balanceText
      .replace(/\./g, '')
      .padStart(7, '0')
  );
}
BackDataDefaultInput();

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

Comments

0

Try to use following function.

var balanceText = "42.54"; //document.getElementById('balanceNumBox').value;
var formattedBalance = balanceText * 100;

function formatInteger(str, max) {
  str = str.toString();
  return str.length < max ? formatInteger("0" + str, max) : str;
}

console.log(formatInteger(formattedBalance, 7));

2 Comments

I'm no longer getting 'Undefined' now. But the output for 42.54 is 0004200, and 4254 is 0425400. So it seems to be appending two final 0's. I have an input mask function to only accept up to 0000.00 i.e. 4 numbers and 2 decimals if that is making any difference
change "var formattedBalance = parseInt(balanceText, 10) * 100;" code in to "var formattedBalance = balanceText * 100;"
0

Answer to my question in case it helps anyone that comes across this page:

function BackDataDefaultInput() {
    var balanceText = document.getElementById('balanceNumBox').value;
    var balance = parseFloat(balanceText) * 100;
    balanceText = String(balance);

while (balanceText.length > 0 && balanceText.length < 7) {
    balanceText = '0' + balanceText;
    }
}

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.