-2

I want to find the percentage of increase or decrease comparing 2 number, the second statement worked, but my test3 has failed if the second number is zero.

const test = Math.abs(((120 - 0) / 0) * 100).toFixed(1) + '%'
const test2 = Math.abs(((50 - 25) / 25) * 100).toFixed(1) + '%'
const test3 = Math.abs(((10000 - 0) / 0) * 100).toFixed(1) + '%'

console.log('test:', test)
console.log('test2:', test2)
console.log('test3', test3)

https://jsfiddle.net/vm1vsf6p/

How to solve this issue?

esther Joo
  • 459
  • 1
  • 5
  • 11
  • `but my test3 has failed` so you say `test` is OK, just `test3` is a failure? – Jaromanda X Oct 11 '17 at 08:08
  • All your tests have the same problem, not just 3. Don't divide by 0. Check if second number is zero before dividing by it. – Nope Oct 11 '17 at 08:10

1 Answers1

-1

You can assume that 0% of anything is 0, so:

function test(num1, num2, divider) {
  var output = 0;

  if (divider) {
    output = Math.abs(((num1 - num2) / divider) * 100).toFixed(1);
  }

  return output+'%';
}

console.log('test:', test(120, 0, 0))
console.log('test2:', test(50, 25, 25))
console.log('test3', test(10000, 0, 0))
Justinas
  • 41,402
  • 5
  • 66
  • 96
  • This would return 0 for case 3. I think the formula is used to indicate a certain gain factor, which in this case should be a large amount (but because of the formula and zero it becomes Infinity instead of certain number). The problem is with formula though, not your code. – Mohit Bhardwaj Oct 11 '17 at 08:12
  • 1
    @MohitBhardwaj Well, I am not fixing this formula, as OP should know better then me. – Justinas Oct 11 '17 at 08:13