簡體   English   中英

將數字四舍五入到相同的距離

[英]Rounding numbers to the same distance

有沒有一種方法可以舍入不同的值,使其具有相同的“距離”? 例如,我有這個值:

100
105.3
110.7
115.1

當我使用Math.round()時,數字之間的距離是不同的:

100
105 // distance is 5 to the previous value
111 // distance is 6 to the previous value 
115 // distance is 4 to the previous value

當然,我可以使用Math.floor()或Math.ceil(),但問題是在運行時值將不同,並且所有數字的距離永遠都不會相同。

我需要SVG對象:

line.setAttribute('x1', Math.round(x1)); // x1 will have values like 85, 130.3, 175.6, 220.89999999999998 for example

如果您僅考慮先前的值,則可以定義一個curried函數用於您感興趣的距離。

以下是使用距離5的演示。 使用map ,您可以在數據數組上運行此命令,以將每個條目強制與上一個條目定義的距離。


編輯

向函數添加了Math.round() ,盡管您也可以在函數的返回值上使用它。

 const previousDistance = (distance) => (previous, current) => { if (current > previous) { return Math.round((current - previous > distance) ? previous + distance : current); } else { return Math.round((previous - current > distance) ? previous - distance : current); } } const previousDistanceFive = previousDistance(5); // outside distance (below) console.log(previousDistanceFive(5, -1)); // -> 0 // inside distance (below) console.log(previousDistanceFive(5, 1.1)); // -> 1 // equal console.log(previousDistanceFive(5, 5)); // -> 5 // inside distance (above) console.log(previousDistanceFive(5, 9.123)); // -> 9 // outside distance (above) console.log(previousDistanceFive(5, 11)); // - > 10 // --- DEMONSTRATION ON Array const arr = [0, 5, 7, 16, 17, 10, 16]; // -> [0, 5, 7, 12, 17, 12, 15] const roundedArr = arr.map((elem, i) => { if (i > 0) { return previousDistanceFive(arr[i - 1], elem); } else { return elem; } }); console.log("Array Demo: ", roundedArr); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM