我在这里工作的是金钱价值。我有一笔未知金额的未知货币(编译时间未知的ofc)。我有多个目标来分配这笔钱。
举个例子:
金额是3.02美元,我将与三个朋友平分,这样每个人都会得到1美元,剩下2美分。现在,由于最后的金额必须是正确的,所以我将剩余的部分在双方之间平分,直到所有剩余的美分都用完。
请注意,同样的方法也适用于日本日元。他们一文不名。例如,32除以3等于10,再加上2作为备用值。
在下面的代码中,cents是一个带有上面提到的拆分剩余部分的decimal.js值(例如,"0.02“或仅为"2")。
for (let i = 0; !cents.isZero(); i++) {
const transactionData = transactionsData[i]
const newAmountCents = new decimal.Decimal(transactionData.amount).plus(new decimal.Decimal("0.01"))
console.log(`New Amount: ${newAmountCents}`)
transactionData.amount = newAmountCents.toString()
newCents = newCents.minus(new decimal.Decimal("0.01"))
}正如你可能看到我的问题所在。我在这里加上"0.01“,然后减去它。但正如我所提到的,这是根据基础货币的小数位数而变化的。如何提取正确的“单位”,并将"0.01“替换为正确的数量?
发布于 2020-08-14 20:56:29
你可以这样做,并创建某种解析函数,它将获得货币值和股票数量,并返回提醒和可能的最低货币值
const parseCoin = (coin, shares) => {
// How mutch zeros after . to use
// Parse coin value as string and
// find it out:
// 3.00 -> 2
// 3 -> 0
let match = String(coin).match(/\.(.*)/);
const decimalFixed = match ? match[1].length : 0;
// Modulus
let remainder = (Number(coin) % shares).toFixed(decimalFixed);
// Find smallest available value
const smallestValue = 1 / 10 ** decimalFixed;
// Return object
return { remainder, smallestValue };
}
// Test
console.log(parseCoin(3.02, 3));
console.log(parseCoin(32, 3));
console.log(parseCoin(2, 2));
console.log(parseCoin(4, 3));
console.log(parseCoin('3.000', 3));
发布于 2020-08-14 20:37:02
将"0.01“设置为字符串变量,该变量在设置货币时设置
const smallestUnitString = "0.01" // In practice you would replace this
// with a function call that looks up the currency name in a table, and
// returns "1" for Yen, and "0.01" for most other currencies.
for (let i = 0; !cents.isZero(); i++) {
const transactionData = transactionsData[i]
const newAmountCents = new decimal.Decimal(transactionData.amount).plus(new decimal.Decimal(smallestUnitString))
console.log(`New Amount: ${newAmountCents}`)
transactionData.amount = newAmountCents.toString()
newCents = newCents.minus(new decimal.Decimal(smallestUnitString))
}发布于 2020-08-14 21:30:44
我刚刚意识到我可以使用coins.dp()并相应地设置一个字符串
function getSmallestUnit(coins: decimal.Decimal) :string{
const dp = coins.dp()
if(dp===0){
return "1"
}else if(dp===1){
return "0.1"
}else if(dp===2){
return "0.01"
}else{
return "0.001"
}
//Continues if there are more currencies that have more decimal places than 3 (have to check this)
}我认为这应该能起到作用。你得检查一下。否则,@tarkh的答案也会起作用:)
https://stackoverflow.com/questions/63412736
复制相似问题