I need to split or divide specific value in 3 part in jquery but result should not be in decilimal. Let me share example : E.g., $800 – split across / 3 : Result $267, $267, and $266 Need function or logic in jquery Thanks in advance
I tried round function of jqeury but its increased the total value.
CodePudding user response:
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;
}