簡體   English   中英

在數組中的多個項目中分配貨幣/數字

[英]Distributing currency/number across multiple items in array

所以我有一種支付分配器,我在浮點運算上苦苦掙扎。 我正在使用 currency.js 來處理數學並安裝了 jQuery,盡管在下面的示例中可能不會使用它

我希望有人能夠支付一筆金額(比如說 50 美元)並將該金額分配到列表中的所有項目中,然后減去它。

所以說我有一個價格清單

prices = [12, 8, 25, 14, 12, 20, 0.5, 8] 
grandTotal = sumArray(prices) //Returns 99.50

然后,一位客戶想要為該發票申請 50 美元,我想將金額平均分配到所有項目中。 所以簡而言之,我想做 99.5-50 = 49.5

amountToPay = 50

我想要的是 output 是這樣的:

/*This sums to 50 and is what need to be subtracted.
In this case I've added the remainder to the last item, but would like the spread to be as even as possible. In currency format, so two decimal places of precision*/
toSubtract = [6, 4, 12.5, 7, 6, 10, 0.25, 4.25]

/*This sums to 49.5, the amount left over when toSubtract is subtracted from prices*/
newPrices = [6, 4, 12.5, 7, 6, 10, 0.25, 3.75] 

但是,是的,真的不知道如何處理分布。 我試圖通過計算百分比(例如 50/99.5)來實現它,但它非常混亂,並且到處都有精度和舍入誤差,我手動捕捉每一個,它只是粗略且難以理解。

根據您的信息,您可以進行簡單的數學運算來計算剩余的部分金額。

total = 99.50;
amount = 50.00;
prices = [12, 8, 25, 14, 12, 20, 0.5, 8];
rate = (total - amount) / total;
newPrices = prices.map(e => ((e * rate).toFixed(2)));
["5.97", "3.98", "12.44", "6.96", "5.97", "9.95", "0.25", "3.98"]

暫無
暫無

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

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