Javascript - Decimals and Zeros on the left

Asked

Viewed 693 times

0

could, help me with the following situation:

I have a Numeric field (21,2) and need to format it for a specific layout, as below.

Example of Input’s:

VALOR1: 3500.31 -> After Formatting: +0000000003500.31

VALOR2: -3000 -> After Formatting: -0000000003000.00

VALOR3: 2000.00 -> After Formatting: +0000000002000.00

I’m using the function below to fill the 0 to the left and validate the signal, but I have a problem, for cases where the input is an integer, so the field in is in the format #.00 :

Output: +0000000000003000

Function:

function leadingZero(value, totalWidth, paddingChar) {

     var length = totalWidth - value.toString().length + 1;
     return Array(length).join(paddingChar || '0') + value;
   };


    if (total_amount >=0){

       var total_amount = '+' + leadingZero(total_amount,20);

    } else {

       var total_amount = '-' + leadingZero(replace(total_amount,'-',''),20);

    }

Thank you!

  • Again? What’s the difference to your other question? https://answall.com/q/257573/5878

  • Although you already have an answer, your question is a bit confused: where does the parameter come from paddingChar? Are you trying to insert new value into the field? This is PHP?

  • @The paddingChar is by default 0, however it is the value to which I will add the string.

  • Sergio’s answer didn’t solve the problem?

  • @In the end, yes..

Show 1 more comment

1 answer

1

I suggest separating in 3 steps:

  • ensure that the number has 2 decimal places
  • have a string of zeros with the maximum possible length to join to the absolute value in question
  • join the signal +/-

and it could be done so:

function leadingZeros(nr) {
  const zeros = '0000000000000000';
  const sign = nr >= 0 ? '+' : '-';
  const numberString = zeros + Math.abs(nr).toFixed(2);
  return sign + numberString.slice(-20);
}

console.log(leadingZeros(3500.31));
console.log(leadingZeros(-3000));
console.log(leadingZeros(3000));
console.log(leadingZeros(2000.00));

  • The evil to use constis that it doesn’t work in IE 10 down. But...

  • @That’s right. Changing to var where is const is already compatible with discontinued browsers.

  • The answer is great, there’s only one problem: from what I understand, the output must have 21 characters. Yours only have 18. I think you can arrange easy.

  • @Ķ thanks, I have adjusted.

  • 1

    Sergio.. thank you very much! for sure a great solution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.