divide number with decimals javascript

前端 未结 8 2052
误落风尘
误落风尘 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:43

    Sounds like a pretty straightforward loop/recursion.

    Here you go

    function divideEvenly(numerator, minPartSize) {
      if(numerator / minPartSize< 2) {
        return [numerator];
      }
      return [minPartSize].concat(divideEvenly(numerator-minPartSize, minPartSize));
    }
    
    console.log(divideEvenly(1000, 333));
    

    To get it to be two decimals of currency multiply both numbers by 100 before calling this function then divide each result by 100 and call toFixed(2).

    Like so

    function divideCurrencyEvenly(numerator, divisor) {
      var minPartSize = +(numerator / divisor).toFixed(2)
      return divideEvenly(numerator*100, minPartSize*100).map(function(v) {
        return (v/100).toFixed(2);
      });
    }
    
    
    console.log(divideCurrencyEvenly(3856, 3));
    //=>["1285.33", "1285.33", "1285.34"]
    
    0 讨论(0)
  • 2021-01-03 13:46
    <button onclick="myFunction(3856,3)">Try it</button>
    
    function myFunction(number,divide) {
            var money = number / divide;
            money = Math.ceil(money * 100) / 100;
            alert(money);   //1285.34
        }
    

    http://jsbin.com/ucuFuLa

    0 讨论(0)
提交回复
热议问题