[英]Check if the value is greater than or equal to the nearest lowest 0.05 in JavaScript
我想檢查一個十進制值是否大於或等於最接近的低 0.05 值
例子
Value | Expected Nearest 0.05 value
11.10 | 11.05
11.11 | 11.10
11.12 | 11.10
11.13 | 11.10
11.14 | 11.10
11.15 | 11.10
我嘗試使用公式
parseFloat((Math.floor(value * 20) / 20).toFixed(2))
但它在 11.10 和 11.15 中失敗。 使用上面的公式,我得到的 output 與值相同,但預期值不同。 我應該使用哪個公式來修復上述測試用例。
您可以將值乘以 100 以暫時刪除所需的兩個小數點,最接近的數字現在變為 5 的倍數,然后您可以將歐幾里德除法的 rest 除以 5 並得到您想要的。
由於需要將 5 的精確倍數帶到最接近的較低值,因此當 rest 等於 0 時,您可以有條件地刪除 5。
公式 function 可能類似於:
const f = (v) => (((Math.floor(v*100) - (Math.floor(v*100) % 5 || 5)) / 100).toFixed(2)); console.log('11.10', f(11.10)); console.log('11.11', f(11.11)); console.log('11.12', f(11.12)); console.log('11.13', f(11.13)); console.log('11.14', f(11.14)); console.log('11.15', f(11.15));
您可以采用偏移量並采用多個底值。
const format = f => Math.floor((f - 0.01) * 20) / 20; console.log([11.10, 11.11, 11.12, 11.13, 11.14, 11.15, 11.16, 11.17, 11.18, 11.19].map(format));
.as-console-wrapper { max-height: 100%;important: top; 0; }
我從您的問題中了解到的是,您想要最接近的最低值,並且答案應該小於值本身。 因此,n 是您需要的最小倍數,而 v 是值,也許您可以嘗試以下操作:
const nearestMultiple = (v) => (Math.floor((v - 0.001) /n) * n).toFixed(2);
查找倍數的基本公式是Math.floor((v/n) * n)
但對於您的獨特情況,我們不希望 function 返回給定的數字,因此減去 0.001。
我不確定我的方式是否最有效,但我會這樣做:
var x = Math.floor(value * 100);
var remainder = x % 5;
if (remainder == 0) {
// deal with dropping down the 11.10 to 11.05
remainder = 5
}
var result = parseFloat((x - remainder) / 100).toFixed(2);
但是,這僅適用於小數點后 2 位的值 - 考慮到小數點后第三位,您需要將其調整為:
var x = value * 100;
var remainder = x % 5;
if (remainder == 0) {
// deal with dropping down the 11.10 to 11.05
remainder = 5
}
var result = parseFloat((x - remainder) / 100).toFixed(2);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.