Search code examples
javascriptrounding

Split quotients of number into array javascript


I need to split or divide specific value in 3 part in jQuery but result should not be in decimal.

Let me share an example :

$800 / 3 
Result  $267, $267, and $266 

I need a function or logic in jQuery or Javascript.

Thanks in advance

I tried round function of jQuery but it's increased the total value.


Solution

  • Math.floor() function always rounds down and returns the largest integer less than or equal to a given number.

    Math.round() function returns the value of a number rounded to the nearest integer.

    console.log(Math.floor(266.66));
    console.log(Math.round(266.66));

    By there, you can create a function to get and array of quotients by looping and checking if the total sum of quotients exceeds to the dividend

    let result = getQoutientsArray(800, 3);
    let result3 = getQoutientsArray(1600, 6);
    let result2 = getQoutientsArray(700, 4);
    
    
    
    console.log(result);
    console.log(result2)
    console.log(result3)
    
    
    function getQoutientsArray(num, divisor) {
      let answers = [];
    
      for (x = 0; x < divisor; x++) {
        let sum = answers.reduce((a, b) => a + b, 0);
        let qoutient = Math.round(num / divisor);
    
        let remaining = divisor - answers.length;
        let remaininganswer = (remaining-1) * Math.floor(num / divisor);
    
        if (sum + qoutient + remaininganswer <= num) {
          answers.push(qoutient);
        } else {
          answers.push(Math.floor(num / divisor));
        }
      }
    
      return answers;
    }