divide number with decimals javascript

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

    If anyone is looking for a randomly distributed vanilla JS solution here is mine:

    function fairDivision(resolution, numerator, denominator) {
        // preserves numerator(n) integrity when dividing into denominator(d) bins
        // remainders are randomly distributed into sequential bins 
        // resolution is number of significant digits after decimal
        // (-'ve resolution for insignificant digits before decimal).
        const n = numerator * Math.pow(10, resolution);
        const remainder = n % denominator;
        const base = (n - remainder) / denominator;  
        const offset = Math.floor(Math.random()*denominator); // index of first 'round-up' bin
    
        let arr = []
        let low= (offset + remainder) % denominator;
    
        let a; let b; let c = (low < offset); //logical units
        for (let i=0; i < denominator; i++) {
            a = (i < low);
            b = (i >= offset);
            if ((a && b) || (a && c) || (b && c)) {
                arr.push(base +1)
            } else{
                arr.push(base)
            }
            arr[i] = arr[i] / Math.pow(10, resolution);
        }
        return arr;
    }
    

提交回复
热议问题