Javascript - Decimals and Zeros on the left

1

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.

Input's example:

VALUE1: 3500.31 - > After Formatting: +00000000000003500.31

VALUE2: -3000 - > After Formatting: -00000000000003000.00

VALUE3: 2000.00 - > After Formatting: +00000000000002000.00

I am using the function below to fill the 0 left and validation of the signal, however I have a problem, for cases where the input is an integer, this way the field is in the format # .00:

Output: +00000000000000003000

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!

    
asked by anonymous 24.11.2017 / 22:28

1 answer

0

I suggest separate 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
  • add the + / -

and this could be done like this:

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));
    
24.11.2017 / 22:59