divide number with decimals javascript

前端 未结 8 2059
误落风尘
误落风尘 2021-01-03 12:54

how can I divide number (money) to x number equally the number could be with one or two decimal or without it

such as 1000 or 100.2 or

8条回答
  •  攒了一身酷
    2021-01-03 13:37

    Since we are talking about money, normally a few cents different doesn't matter as long as the total adds up correctly. So if you don't mind one payment possibly being a few cents greater than the rest, here is a really simple solution for installment payments.

    function CalculateInstallments(total, installments) {
      // Calculate Installment Payments
      var pennies = total * 100;
      var remainder = pennies % installments;
      var otherPayments = (pennies - remainder) / installments;
      var firstPayment = otherPayments + remainder;
    
      for (var i = 0; i < installments; i++) {
        if (i == 0) {
          console.log("first payment = ", firstPayment / 100);
        } else {
          console.log("next payment = ", otherPayments / 100);
        }
      }
    }

    Since you said you wanted the highest payment at the end you would want to modify the if statement in the for loop: if (i==installments-1) { //last payment }

提交回复
热议问题