我试图在js中实现十进制值的减量功能
单击按钮时,应该会发生以下情况
1.22 -> 1.21
3.00 -> 2.99
1.2345 -> 1.2344我怎么能这样做,下面是我的代码
var decimals = 1,
stringC = String(positionData.volume),
value = parseFloat(positionData.volume);
if (stringC.includes(".")) {
const splitted = stringC.split(".");
decimals = splitted[1];
}
const length = decimals?.length;
if (length > 0) {
decimals = "0.";
for (let i = 0; i < length; i++) {
if (i == length - 1) {
decimals += "1";
}
decimals += "0";
}
}
console.log(decimals);
decimals = parseFloat(decimals).toFixed(2);
setCloseValue((value) =>
(parseFloat(value) + decimals).toString()
);上面是我的代码,但它将值作为字符串追加。
发布于 2022-10-13 14:37:41
const decrementVarable = (decimal)=>{
let decToString = decimal.toString().split('.')
if(decToString.length > 1){
let value = decToString[1]
let number = Number('1'+ '0'.repeat(value.length))
let numWithoutDecimal = ((decimal * number)-1)/number
return numWithoutDecimal
}
return (decimal-1);
}
使用这段代码只需通过小数点
发布于 2022-10-13 14:39:08
浮点数通常是混乱的。如果你真的需要它是100%精确,使用一个整数变量,在每次迭代中增加1,测试它何时达到100,然后,在实际计算中,取你的变量除以100,得到你需要的十进制值。
https://stackoverflow.com/questions/74057402
复制相似问题