divide number with decimals javascript

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

    There is an issue on @user633183's distribute but only happen when the divider is lower than 3.

    distribute(2, 2, 560.3)
    // [ '280.15' , '280.14']
    
    distribute(2, 1, 74.10)
    // [ '74.09' ]
    
    distribute(2, 1, 74.60)
    // [ '74.59' ]
    

    I rewrote the answer by Guffa into javascript

    const distribute = (precision, divider, numerator) => {
    const arr = [];
      while (divider > 0) {
        let amount = Math.round((numerator / divider) * Math.pow(10, precision)) / Math.pow(10, precision);
        arr.push(amount);
        numerator -= amount;
        divider--;
      }
      return arr.sort((a, b) => b-a);
    };
    

    Here are the results

    distribute(0, 7, 100)
    => [ 15, 15, 14, 14, 14, 14, 14 ]
    
    distribute(1, 7, 100)
    => [ 14.3, 14.3, 14.3, 14.3, 14.3, 14.3, 14.2 ]
    
    distribute(2, 7, 100)
    => [ 14.29, 14.29, 14.29, 14.29, 14.28, 14.28, 14.28 ]
    
    distribute(3, 7, 100)
    => [ 14.286, 14.286, 14.286, 14.286, 14.286, 14.285, 14.285 ]
    
    distribute(4, 7, 100)
    => [ 14.2858, 14.2857, 14.2857, 14.2857, 14.2857, 14.2857, 14.2857 ]
    
    // and of course
    
    distribute(2, 2, 560.3)
    => [ 280.15, 280.15 ]
    
    distribute(2, 1, 74.10)
    => [ 74.1 ]
    
    distribute(2, 1, 74.60)
    => [ 74.6 ]
    

提交回复
热议问题