简体   繁体   English

在数组中的多个项目中分配货币/数字

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

So I have a sort of payment splitter and I'm struggling with floating point operations.所以我有一种支付分配器,我在浮点运算上苦苦挣扎。 I'm using currency.js to handle the maths and have jQuery installed too, though probably won't use it in the example below我正在使用 currency.js 来处理数学并安装了 jQuery,尽管在下面的示例中可能不会使用它

I want someone to be able to pay an amount (let's say $50) and spread that amount across all the items in the list, and subtract it.我希望有人能够支付一笔金额(比如说 50 美元)并将该金额分配到列表中的所有项目中,然后减去它。

So say I have a list of prices所以说我有一个价格清单

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

Then a customer wants to apply $50 to that invoice, and I want to spread the amount out evenly across all items.然后,一位客户想要为该发票申请 50 美元,我想将金额平均分配到所有项目中。 So in short I want to do 99.5-50 = 49.5所以简而言之,我想做 99.5-50 = 49.5

amountToPay = 50

What I want is to output something like this:我想要的是 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] 

But yeah, really not sure how to even approach distribution.但是,是的,真的不知道如何处理分布。 I have attempted to it by calculating the percentage (eg 50/99.5), but it was extremely messy and still had precision & rounding errors everywhere and I was manually catching each one and it was just gross and incomprehensible.我试图通过计算百分比(例如 50/99.5)来实现它,但它非常混乱,并且到处都有精度和舍入误差,我手动捕捉每一个,它只是粗略且难以理解。

Based on your info, you can do simple math to calculate the partial amounts left.根据您的信息,您可以进行简单的数学运算来计算剩余的部分金额。

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