2 回答

TA貢獻1833條經驗 獲得超4個贊
使用取模運算符
但是,除以分數 (.05) 可能會產生不完美的結果,因此最好乘以 20 并檢查是否有分數提醒(模數 1)。
@Thomas Sablik 的回答也有效,并解釋了乘以 20。
const isPoint05 = x => x * 20 % 1 === 0;
const test = (...args) => args.forEach(x => console.log(x, isPoint05(x)));
test(6, 3.1, 4.05, 53.65, 3.254, 6.22, 7.77, 7.33);
為了說明分數除法的挑戰(取決于 JavaScript 實現,我在 chrome 上得到 0.049999999999999614):
console.log(7 % 0.05);

TA貢獻1859條經驗 獲得超6個贊
您可以將數字乘以 20 并四舍五入:
if (Math.round(x * 20) !== x * 20) {
// not counted in 0.05 steps, eg. 1.234
} else {
// counted in 0.05 steps, eg. 1.25
}
此 if 語句檢查“這些數字是否在小數點后有 2、1 或沒有數字,并且以 0.05 步計算”,因為以 0.05 步計算的數字乘以 20 是整數(Math.round(x * 20) !== x * 20為 false),例如:
0.05 * 20 = 1
1.25 * 20 = 25
和其他數字不是整數(Math.round(x * 20) !== x * 20是真的),例如:
0.04 * 20 = 0.8
1.251 * 20 = 25.2
但是將這個 if 語句與 with 一起使用是一個壞主意,因為生成太多其他Math.random數字的可能性很高,以至于遞歸會導致堆棧溢出。Math.random
更好的方法是生成您想要的數字
x = Math.round(Math.random() * 20 * 100) / 20
添加回答
舉報