如何计算两个数字之间的节省百分比?

83

我有两个数字,第一个是原始价格,第二个是折扣价格。

如果用户以第二个价格购买商品,我需要计算出他们节省了多少百分比。

example
25, 10 = 60%  
365, 165 = 55%

我不知道计算这个的公式。


3
@ShreevatsaR - 你希望我重新表述这个问题,以便说“用PHP公式计算两个数字之间的节省百分比”,这样人们就可以编写 $diff = (($listPrice - $actualPrice) / ($listPrice)) * 100;。无论如何,你不能不使用公式来编写程序,因此,这个问题与编程有关。 - Hailwood
我认为如果你明确指出它与编程有关,它会得到改进。按照现在的写法,它只是一个数学问题。 - r12
我确实去了math.stackexchange.com上问这个问题,但那里似乎有点不合适,因为我甚至找不到标记“公式”或“百分比”! - Hailwood
11个回答

211

我知道这篇文章相对较旧,但我认为这是一个好的机会来分享一下。我在Yahoo上找到了一个很好的解释:

Let's say you have two numbers, 40 and 30.  

  30/40*100 = 75.
  So 30 is 75% of 40.  

  40/30*100 = 133. 
  So 40 is 133% of 30. 

The percentage increase from 30 to 40 is:  
  (40-30)/30 * 100 = 33%  

The percentage decrease from 40 to 30 is:
  (40-30)/40 * 100 = 25%. 

These calculations hold true whatever your two numbers.

原始帖子


1
讲解得很清楚,兄弟。 - Emtiaz Zahid

38
((list price - actual price) / (list price)) * 100%
例如:
((25 - 10) / 25) * 100% = 60%

1
从技术上讲,您应该先将 100 相乘,然后打印 % 符号。 "100%" 的值并不总是与 "100" 的值相同。 - r12
2
实际上,百分比计算对我来说总是有点奇怪。 - Andy White
4
"%" 表示 "per cent",意思是 "1/100",而 "100%" 表示 100/100 = 1。因此,用 "100%" 乘以一个数与用 "1" 相乘是相同的:它不改变这个数的值。所以,0.6 = 0.6 * 100% = 60%,同样地,1/2 = 1/2 * 100% = 50%,等等。 - ShreevatsaR

17

我看到这是一个非常老的问题,但这就是我计算两个数字之间百分比差异的方法:

(1 - (oldNumber / newNumber)) * 100

因此,从30到40的百分比差异为:

(1 - (30/40)) * 100 = +25% (meaning, increase by 25%)

从40到30的百分比差异为:

(1 - (40/30)) * 100 = -33.33% (meaning, decrease by 33%)

在php中,我使用类似这样的函数:

function calculatePercentage($oldFigure, $newFigure) {
        if (($oldFigure != 0) && ($newFigure != 0)) {
            $percentChange = (1 - $oldFigure / $newFigure) * 100;
        }
        else {
            $percentChange = null;
        }
        return $percentChange;
}

11

公式为(原价-折扣价)/原价。即 (365-165)/365 = 0.5479...


(9.999.999 - 369.990) / 9.999.999 = 0,9630009963000996300099630009963?但它应该是超过2700%,对吧? - chiperortiz

6
    function calculatePercentage($oldFigure, $newFigure)
{
    $percentChange = (($oldFigure - $newFigure) / $oldFigure) * 100;
    return round(abs($percentChange));
}

1
虽然这段代码片段可能解决了问题,但包括解释真的有助于提高您的帖子质量。请记住,您正在为未来的读者回答问题,而这些人可能不知道您的代码建议原因。请尽量不要在代码中添加过多的解释性注释,这会降低代码和解释的可读性! - kayess

5

100% - 折扣价格 / 原价


@Klas:这正是所期望的。 - Ignacio Vazquez-Abrams

2

如果总数是:200,其中得到50分

那么50在200中的百分比为:

(50/200)*100 = 25%


1
我曾经为我的一个应用程序做了同样的百分比计算器,其中我们需要显示如果选择“年度计划”而不是“月度计划”可以节省的百分比。它可以帮助你在给定的时间内节省一定金额。我已经将其用于订阅。

每月支付一年 - 2028 一次性支付一年 - 1699

1699是2028的16.22%减少。

公式: 减少的百分比= |2028-1699|/2028 = 329/2028 = 0.1622 = 16.22%

代码:

func calculatePercentage(monthly: Double, yearly: Double) -> Double {
    let totalMonthlyInYear = monthly * 12
    let result = ((totalMonthlyInYear-yearly)/totalMonthlyInYear)*100
    print("percentage is -",result)
    return result.rounded(toPlaces: 0)
}

使用方法:

 let savingsPercentage = self.calculatePercentage(monthly: Double( monthlyProduct.price), yearly: Double(annualProduct.price))
 self.btnPlanDiscount.setTitle("Save \(Int(savingsPercentage))%",for: .normal)

对于将百分比四舍五入至 Double 数据类型的扩展使用:

extension Double {
/// Rounds the double to decimal places value
func rounded(toPlaces places:Int) -> Double {
    let divisor = pow(10.0, Double(places))
    return (self * divisor).rounded() / divisor
   }
}

我已经附上了图片以便理解:

Percentage Calc - Subscription


0

这是具有反转选项的函数

它将返回:

  • 'change' - 可用于您的模板中的CSS类的字符串
  • 'result' - 简单结果
  • 'formatted' - 格式化结果

function getPercentageChange( $oldNumber , $newNumber , $format = true , $invert = false ){

    $value      = $newNumber - $oldNumber;

    $change     = '';
    $sign       = '';

    $result     = 0.00;

    if ( $invert ) {
         if ( $value > 0 ) {
        //  going UP
            $change             = 'up';
            $sign               = '+';
            if ( $oldNumber > 0 ) {
                $result         = ($newNumber / $oldNumber) * 100;
            } else {
                $result     = 100.00;
            }

        }elseif ( $value < 0 ) {        
        //  going DOWN
            $change             = 'down';
            //$value                = abs($value);
            $result             = ($oldNumber / $newNumber) * 100;
            $result             = abs($result);
            $sign               = '-';

        }else {
        //  no changes
        }

    }else{

        if ( $newNumber > $oldNumber ) {

            //  increase
            $change             = 'up';

            if ( $oldNumber > 0 ) {

                $result = ( ( $newNumber / $oldNumber ) - 1 )* 100;

            }else{
                $result = 100.00;
            }

            $sign               = '+';

        }elseif ( $oldNumber > $newNumber ) {

            //  decrease
            $change             = 'down';

            if ( $oldNumber > 0 ) {

                $result = ( ( $newNumber / $oldNumber ) - 1 )* 100;

            } else {
                $result = 100.00;
            }

            $sign               = '-';

        }else{

            //  no change

        }

        $result = abs($result);

    }

    $result_formatted       = number_format($result, 2);

    if ( $invert ) {
        if ( $change == 'up' ) {
            $change = 'down';
        }elseif ( $change == 'down' ) {
            $change = 'up';
        }else{
            //
        }

        if ( $sign == '+' ) {
            $sign = '-';
        }elseif ( $sign == '-' ) {
            $sign = '+';
        }else{
            //
        }
    }
    if ( $format ) {
        $formatted          = '<span class="going '.$change.'">'.$sign.''.$result_formatted.' %</span>';
    } else{
        $formatted          = $result_formatted;
    }

    return array( 'change' => $change , 'result' => $result , 'formatted' => $formatted );
}

1
这可以根据输入完全重新格式化为单个计算。 - Mike Q

0

我认为这个公式已经足够涵盖了。

((curr value - base value) / (curr value)) * 100%

在编程中,我们基本上只是:

  • 如果两个数字都不为0,则执行计算。
  • 如果当前值为0,则从基础值返回-100%的差异。
  • 如果两个数字都为0,则返回0(我们无法除以0)

Powershell示例:

从变量中剥离任何非数值内容并执行计算

Function Get-PercentageSaved {
    #((curr value - base value) / (curr value)) * 100%
    param(
        [Parameter(Mandatory = $false)][string]$CurrVal = $null,
        [Parameter(Mandatory = $false)][string]$BaseVal = $null
    )
    $Result = $null
    Try {

        $CurrVal = [float]($CurrVal -replace '[^0-9.]', '')
        $BaseVal = [float]($BaseVal -replace '[^0-9.]', '')

        if (-Not($null -eq $CurrVal) -And (-Not($null -eq $BaseVal))) {
            if ($CurrVal -eq 0) {
                If ($BaseVal -eq 0) {
                    $Result = 0
                } Else {
                    $Result = -100
                }
            }
            else {
                $Result = [math]::Round([float]((($CurrVal - $BaseVal) / $CurrVal) * 100),2)
            }
        }
    }
    Catch {}
    Return [float]$Result
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接