gpt4 book ai didi

javascript - 如何使 handleChange 方法正确地将用户输入格式化为所需的范围?

转载 作者:行者123 更新时间:2023-12-01 16:09:54 26 4
gpt4 key购买 nike

我有以下字段,我希望通过根据数据添加前导零和尾随零来使所需的输出采用 XX.xxxxxx 的格式

<TextBoxField
id="location-latitude-control"
title="Required: Latitude"
name="location.latitude"
value={location.latitude}
handleChange={this.handleChange}
handleBlur={this.handleBlur}
/>

我该怎么做才能修复我的 handleChange 方法以正确格式化用户的输入:

handleChange = 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;
}
}

纬度的预期行为:

"7.0" should convert to "07.000000"
"12.1234561" should convert to "12.123456"

最佳答案

您可以使用 Math.powtoFixed

let handleChange = (val) => {
const len = (+val).toString().length;
if (len > 1) {
const pow = val > -1 ? len - 2 : len - 3;

return "" + (val / Math.pow(10, pow)).toFixed(6);
}
return "0" + (+val).toFixed(6);
};

console.log(handleChange("7.0")); //07.000000
console.log(handleChange("123456789")); //12.345679
console.log(handleChange("12")); //12.000000
console.log(handleChange("1")); //1.0000000
console.log(handleChange("-123")); //-12.300000
console.log(handleChange("1234")); //12.340000

关于javascript - 如何使 handleChange 方法正确地将用户输入格式化为所需的范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63028415/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com