简体   繁体   English

使用Decimal.js计算两个数字之间的百分比增加/减少百分比的正确方法是什么?

[英]What is the correct way to calculate percentage increase/decrease between two numbers using Decimal.js?

Desired Behaviour 期望的行为

Show percentage increase/decrease of new_value in comparison to old_value , showing negative indicator when there has been a decrease, and 4 decimal places (with trailing zeros if necessary). 显示的百分比增加/下降new_value相比old_value ,示出了当出现了降低,并且4位小数(与尾随零如果必要的话)负指示符。

Actual Behaviour 实际行为

Good
If old_value is 38.1200 and new_value is 19.0600 result is -50.0000 如果old_value38.1200new_value19.0600结果为-50.0000

Not so good 不太好
If old_value is 0.0000 and new_value is 1.0000 result is Infinity (I expect the result to be 100.0000 . Edit : I now realise that there is no such thing as a percentage increase from 0 to anything, per posts like this ). 如果old_value0.0000new_value1.0000结果是Infinity (我希望得到的结果是100.0000 编辑 :我现在认识到,有没有这样的事情从增长百分比0到任何东西,每个职位像这样 )。

What I've Tried 我尝试过的

 var old_value = new Decimal(0.0000); var new_value = new Decimal(1.0000); var difference = new_value.sub(old_value).dividedBy(old_value).times(100).toFixed(4, 7); // without using Decimal.js, the equation above would be: // (new_value - old_value) / old_value * 100 $(".result").text(difference.toString()); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/7.3.0/decimal.min.js"></script> <p class="result"></p> 

I am assuming the equation is correct, it was just the Infinity result that threw me, so here is solution to "handle" the issue: 我假设方程式是正确的,只是Infinity结果使我受挫,所以这里是“处理”问题的解决方案:

 var old_value = "38.1200"; if (old_value === "0.0000") { // show an infinity sign or something $(".result").text("HI!!"); } else { old_value = new Decimal(old_value); var new_value = new Decimal(19.0600); var difference = new_value.sub(old_value).dividedBy(old_value).times(100).toFixed(4, 7); $(".result").text(difference.toString()); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/decimal.js/7.3.0/decimal.min.js"></script> <p class="result"></p> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM