为什么该方法将padEnd返回为未定义?

时间:2020-07-22 16:09:34

标签: javascript reactjs

使用以下方法,当我输入7.0时,出现以下错误:

Unhandled Rejection (TypeError): Cannot read property 'padEnd' of undefined

formatInput = (value) => {
  const numsAfterDot = 6;
  const isNegative = value < 0;
  const hasDecimals = value.includes(".");
  let absolute = Math.abs(value).toString();
  if (isNaN(absolute)) return;
  else {
    const split = absolute.split(".");
    let start = hasDecimals ? split[0] : absolute.slice(0, 2);
    let rest = hasDecimals ? split[1] : absolute.slice(2, numsAfterDot)
    start = start.padStart(2, "0");
    rest = rest.padEnd(numsAfterDot, "0");
    const result = `${start}.${rest}`;
    return isNegative ? `-${result}` : result;
  }
};

有人可以帮我解决这个问题吗? error

预期输出:

"7.0" should converts to "07.000000"
"12" should converts to "12.000000"
".12" should converts to "00.120000"
"-123" should converts to "-12.300000"
"123456" should converts to "12.345600"

1 个答案:

答案 0 :(得分:1)

出现错误是因为您测试发送的字符串是否有小数点。

const hasDecimals = value.includes(".");

然后将其转换为绝对值。

let absolute = Math.abs(value).toString();

当您这样做时,它不再具有小数点,因此拆分将为['7']

因此没有split[1],因此为什么它没有定义。

您的代码有点复杂。我将拆分,如果长度不为2,我会将字符串拆分为两部分,然后填充它。

function custPad (str) {
  // convert to number
  const num = +str;
  // check if negative
  const neg = num < 0 ? '-' : '';
  // get rid of negative, split it at decimal
  const parts = Math.abs(num).toString().split('.');
 
  // if no decimal, than break it up
  if (parts.length === 1) {
    const nums = parts[0];
    // grab first two numbers
    parts[0] = nums.substr(0,2);
    // grab remaining
    parts[1] = nums.substr(2, 6);
  }

  // build the new string with the padding
  return neg + parts[0].padStart(2, '0') + "." + parts[1].padEnd(6, '0').substr(0,6);

}


console.log("7.0", custPad("7.0"))
console.log("7", custPad("7"))
console.log("0.12", custPad("0.12"));
console.log("123", custPad("123"));
console.log("-12", custPad("-12"));
console.log("123456", custPad("123456"));
console.log("12345678911111111", custPad("12345678911111111"));