How to calculate percentage when old value is ZERO

后端 未结 9 980
甜味超标
甜味超标 2021-01-31 16:20

I need the logic for the following situation. I am clueless in doing this.

Consider for January I have 10$ revenue and f

9条回答
  •  深忆病人
    2021-01-31 16:42

    When both values are zero, then the change is zero.

    If one of the values is zero, it's infinite (ambiguous), but I would set it to 100%.

    Here is a C++ code (where v1 is the previous value (old), and v2 is new):

    double result = 0;
    if (v1 != 0 && v2 != 0) {
      // If values are non-zero, use the standard formula.
      result = (v2 / v1) - 1;
    } else if (v1 == 0 || v2 == 0) {
      // Change is zero when both values are zeros, otherwise it's 100%.
      result = v1 == 0 && v2 == 0 ? 0 : 1;
    }
    result = v2 > v1 ? abs(result) : -abs(result);
    // Note: To have format in hundreds, multiply the result by 100.
    

提交回复
热议问题