最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

math - calculate % change in javascript - Stack Overflow

programmeradmin1浏览0评论
var current = 12000;
var june = 14600;
var may = 11200;

I want percent change with respect to 'current' month parameter. The output should be in percent and it can add or subtract w.r.t. the current month. How to do this?

var current = 12000;
var june = 14600;
var may = 11200;

I want percent change with respect to 'current' month parameter. The output should be in percent and it can add or subtract w.r.t. the current month. How to do this?

Share Improve this question edited Jun 21, 2015 at 18:19 Anuj Garg 5827 silver badges22 bronze badges asked Jun 21, 2015 at 17:51 Sagar SuryawanshiSagar Suryawanshi 1951 gold badge1 silver badge11 bronze badges 0
Add a comment  | 

4 Answers 4

Reset to default 31

Note that if one of your values is 0 you will get either -100% or Infinity%. This solves that problem:

   function percIncrease(a, b) {
        let percent;
        if(b !== 0) {
            if(a !== 0) {
                percent = (b - a) / a * 100;
            } else {
                percent = b * 100;
            }
        } else {
            percent = - a * 100;            
        }       
        return Math.floor(percent);
    }

Its simple maths:

var res=(current-june)/current*100.0;
var percentchange = (june - current) / current * 100.0;

If your answer is a negative number then this is a percentage increase else decrease.

It isn't an easy task to handle specials cases, increase or decrease, rounding, over 100%, etc.

function calcPc(n1,n2){
  return (((n2 - n1) / n1 * 100).toLocaleString('fullwide', {maximumFractionDigits:3}) + "%");
}
   
   
   console.log(
   
     " May: "   , calcPc(11200,12000) ,
     "\nJune:" ,  calcPc(14600,12000)
   
   )

发布评论

评论列表(0)

  1. 暂无评论