Stack Overflow Asked by dev101 on November 27, 2021
Using the following method, when I am entering 7.0
I get the following error:
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;
}
};
Can someone please help me solve this?
Expected output:
"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"
You get the error because you test to see if the string you send in has a decimal point.
const hasDecimals = value.includes(".");
You then convert it to absolute.
let absolute = Math.abs(value).toString();
When you do that it no longer has a decimal point, so the split is going to be ['7']
so there is no split[1]
, hence why it is undefined.
Your code is a bit complicated. I would just split, if it is not a length of 2, I would split the string up into two parts and then pad it.
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"));
Answered by epascarello on November 27, 2021
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP