I have an int named Value with a random number.
I need to display in a label the percentage (0–100%), according to Value.
For example, if Value is 30 of 60, then the percentage should be 50%. What formula should I use?
(random_value / max_value) * 100
something like this?
if($value > 30 && $value < 60) {
$percentage = '50%';
} else {
$percentage = ($value / $max_value) * 100 . '%';
}
Related
I basically have a number, say 100.
I can increase it by 10 percent every time. So, :
1st run it would become 110,
2nd 121,
3rd 133 and so on.
I can have count of how much the value was increased. But how to expotentialy decrease the amount knowing the number of times it has been increased back to 100?
Is there a way to do it with simple math op like ** instead of looping the current value amount of times it has been altered by 10 percents?
I know I can just store it in additionl column like base_number=100 or something when I need the basic value, but I would like to know if its possible to do by one-liner calculations?
So your basic question is, how do you invert and find x_0 given a known n and:
x_n = x_0 * 1.1^n
Looks like we can simply divide through by 1.1^n
x_n/(1.1^n) = x_0
So you can either calculate 1.1^n with pow(1.1, n) and divide x_n (your "increased" value) by that, or just loop and reduce like you increased:
//1.
$original = $increased/pow(1.1, n);
//2.
$original = $increased;
for ($i = 0; $i < n; $i++) {
$original = $original / 1.1;
}
So in your example, let's say our $increased is known to be 133, and n=3. Then using the first method:
$original = 133 / (1.1^3) = 133 / 1.33 = 100
Let's make a simple example and try to find a formula :
100 * 1.10 = 110;
110 * 1.10 = 121;
121 * 1.10 = 133.1;
So right now we have :
basic_number (will be bn) * increase_value (will be iv) = basic_number2;
bn2 * iv = bn3;
bn3 * iv = bn4;
We can write it too :
bn * iv = bn2;
bn * iv * iv = bn3;
bn * iv * iv * iv = bn4;
And so we have the beginning of a formula :
bn * iv^3 = bn4;
Now what you will have as data according to your post is :
X : the number of increase
bnX : the basic number increase X time
iv : the increase value
And you want to find bn according to those value :
bn * iv^X = bnX;
bn = bnX / iv^X;
bn = bnX / (iv * iv * iv ... * iv); // X time
So with PHP it could look like this :
$X = /* the number of incease */;
$bnX = /* the basic number increase X time */;
$iv = /* the increase value */;
for($i = 0; $i < $X; $i++) {
$bnX = $bnX / $iv;
}
This way you will if you echo $bnX; at the end of the loop, you should get your basic number !
You can try to make a php formula to do it and use it every time :
// 1/ Using a loop
function getBasicNumber($bnX, $X, $iv) {
for($i = 0; $i < $X; $i++) {
$bnX = $bnX / $iv;
}
return $bnX;
}
EDIT
// 2/ Using pow
function getBasicNumber($bnX, $X, $iv) {
return $bnX / pow($X, $iv);
}
// 3/ Using '**'
function getBasicNumber($bnX, $X, $iv) {
return $bnX / $X**$iv;
}
This way you just have to do :
echo getBasicNumber(133.1, 3, 1.10); // 100 here for example
Hope it's clear? But still, it's more a maths problem than a programming one
I want to increase the value of a number on a curve. I have:
for($i=1; $i<=40; $i++){
$number = cosh($i);
echo $number;
}
This example curves up too fast. How to do I add a variable to this code that will allow me to adjust the rate the number increases? I looking to adjust the slope of the curve. I'm not looking to adjust the value of the beginning number (ie $i = $i*.3).
Countless ways to do this. Here are two:
Change the exponent of $i. Since your starting value is 1, and 1 raised to any power is still 1. Choose a power in the range (0, 1) (non-inclusive), e.g.:
$number = cosh(pow($i, 0.25));
Slightly more general - a power or a multiple of the difference between $i and starting value:
$start = 1;
$end = 40;
$const = 0.01;
for ($i = $start; $i <= $end; $i++) {
$number = cosh($start + ($i - $start) * $const);
// ...
// or...
$power = 0.25;
for ($i = $start; $i <= $end; $i++) {
$number = cosh($start + pow($i - $start, $power));
// ...
// or a combination of both.
if you don't want to change $i in the for definition, change it within the function call:
for($i=1; $i<=40; $i++){
$number = cosh($i*.3);
echo $number;
}
I tried to calculate the percentage of one value (total sales for one item) compared to another (total sales for all items) based on what it says here and came up with this code:
private double GetPercentageOfItem(decimal totPrice, decimal grandTotalPrice)
{
if ((totPrice <= 0.0M) || (grandTotalPrice <= 0.0M))
{
return 0.0;
}
if (totPrice == grandTotalPrice)
{
return 100.0;
}
//First: work out the difference (increase) between the two numbers you are comparing.
//Increase = New Number - Original Number.
double diff = Convert.ToDouble(grandTotalPrice) - Convert.ToDouble(totPrice);
//Then: divide the increase by the original number and multiply the answer by 100.
double prcntg = diff / Convert.ToDouble(totPrice);
//% increase = Increase ÷ Original Number × 100.
return prcntg*100;
}
grandTotalPrice is the sum of all totalSales values in a dataset:
decimal grandTotalPrice = 0.0M;
. . .
foreach (DataRow productUsageByMonthDataRow in dtUsage.Rows)
{
grandTotalPrice = grandTotalPrice + Convert.ToDecimal(productUsageByMonthDataRow["TotalPrice"]);
}
totPrice are the individual TotalPrice values.
Instead of getting values I expect, though, such as 3.something percent (or 2.N, or 1.N, or 0.N), I'm getting outrageous values such as "318940.70340793" in each Percentage member, which is assigned like so:
foreach (DataRow productUsageByMonthDataRow in dtUsage.Rows)
{
. . .
Decimal totPrice
Convert.ToDecimal(productUsageByMonthDataRow["TotalPrice"]);
. . .
var pupd = new ProduceUsagePivotData
{
ItemCode = itemCode,
ItemDescription = desc,
Unit = unit,
MonthYear = monthYear,
Quantity = qty,
TotalPrice = totPrice,
IsContractItem = contractItem,
Percentage = GetPercentageOfItem(totPrice, grandTotalPrice)
};
. . .
In the data I am testing, grandTotalPrice is 687149.867, and the first Total Sales value is 215.38; so how does that equate to 318940.70340793?
UPDATE
Thanks to the answers of several (I accepted the first one), as well as my own inimitable flourishes, curlicues, and baroque gingerbreading, I ended up with this:
private double GetPercentageOfItem(decimal totPrice, decimal grandTotalPrice)
{
if ((totPrice <= 0.0M) || (grandTotalPrice <= 0.0M))
{
return 0.0;
}
if (totPrice == grandTotalPrice)
{
return 100.0;
}
double d = Convert.ToDouble(totPrice) / Convert.ToDouble(grandTotalPrice) * 100;
return Math.Round(d, 2);
}
Based on what you are saying you expect... It seems as though you are looking for what percent item(1) is of the total.
For example if Item1 = $10 and the totalCost = $100
Then the percent you are looking for is 10%?
In this case you simply need to divide the the itemCost by the totalcost and multiply by 100
var percent = itemCost / totalCost * 100;
(10 / 100 * 100 ) = 10%
If you are in fact looking for the percent increase then the number you are getting is correct.
Think of when someone says "We have seen a 200% increase" what this really means is the value has doubled... So if we look at the number you got 318940.70340793%
If we divide this by 100, we get 3189.407.
3189 * 215 = 687149.867 (approx)
So if you are looking for percent increase than the values you are getting are correct, however if you are looking for the percent cost of Item1 compared with the GrandTotal then use my above formula.
Hope this helps!
I am using woocommerce and I'd like to shorten all product prices to K (for thousand) and M (for million). So 150,000 would be 150K, 2,500,000 would be 2,5M etc. How do I do that?
Thank you!
add_filter('woocommerce_price_html','rei_woocommerce_price_html', 10, 2);
add_filter('woocommerce_sale_price_html','rei_woocommerce_price_html', 10, 2);
function rei_woocommerce_price_html($price, $product) {
$currency = get_woocommerce_currency_symbol( );
$price = $currency . custom_number_format($product->get_price(),1);
return $price;
}
function custom_number_format($n, $precision = 3) {
if ($n < 1000000) {
// Anything less than a million
$n_format = number_format($n);
} else if ($n < 1000000000) {
// Anything less than a billion
$n_format = number_format($n / 1000000, $precision) . 'M';
} else {
// At least a billion
$n_format = number_format($n / 1000000000, $precision) . 'B';
}
return $n_format;
}
couple things to note here..
woocommerce_sale_price_html does not include the original price.. you have to code it.
the logic on currency format on WooCommerce is ignored. you may have to adjust the code according to your needs.
I think this will help you
<?php
$n = 265460;
function bd_nice_number($n) {
$n = (0+str_replace(",","",$n));
if(!is_numeric($n)) return false;
if($n>1000000000000) return round(($n/1000000000000),1).'-T';
else if($n>1000000000) return round(($n/1000000000),1).'B';
else if($n>1000000) return round(($n/1000000),1).'M';
else if($n>1000) return round(($n/1000),1).'K';
return number_format($n);
}
$v = bd_nice_number($n);
echo $v;
?>
I have two numbers, the first, is the original price, the second, is the discounted price.
I need to work out what percentage a user saves if they purchase at the second price.
example
25, 10 = 60%
365, 165 = 55%
What I dont know is the formula to calculate this.
I know this is fairly old but I figured this was as good as any to put this. I found a post from yahoo with a good explanation:
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.
Original Post
((list price - actual price) / (list price)) * 100%
For example:
((25 - 10) / 25) * 100% = 60%
I see that this is a very old question, but this is how I calculate the percentage difference between 2 numbers:
(1 - (oldNumber / newNumber)) * 100
So, the percentage difference from 30 to 40 is:
(1 - (30/40)) * 100 = +25% (meaning, increase by 25%)
The percentage difference from 40 to 30 is:
(1 - (40/30)) * 100 = -33.33% (meaning, decrease by 33%)
In php, I use a function like this:
function calculatePercentage($oldFigure, $newFigure) {
if (($oldFigure != 0) && ($newFigure != 0)) {
$percentChange = (1 - $oldFigure / $newFigure) * 100;
}
else {
$percentChange = null;
}
return $percentChange;
}
The formula would be (original - discounted)/original. i.e. (365-165)/365 = 0.5479...
function calculatePercentage($oldFigure, $newFigure)
{
$percentChange = (($oldFigure - $newFigure) / $oldFigure) * 100;
return round(abs($percentChange));
}
100% - discounted price / full price
If total no is: 200
and getting 50 number
then take percentage of 50 in 200 is:
(50/200)*100 = 25%
I have done the same percentage calculator for one of my app where we need to show the percentage saved if you choose a "Yearly Plan" over the "Monthly Plan". It helps you to save a specific amount of money in the given period. I have used it for the subscriptions.
Monthly paid for a year - 2028
Yearly paid one time - 1699
1699 is a 16.22% decrease of 2028.
Formula: Percentage of decrease = |2028 - 1699|/2028 = 329/2028 = 0.1622
= 16.22%
Code:
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)
}
Usage:
let savingsPercentage = self.calculatePercentage(monthly: Double( monthlyProduct.price), yearly: Double(annualProduct.price))
self.btnPlanDiscount.setTitle("Save \(Int(savingsPercentage))%",for: .normal)
The extension usage for rounding up the percentage over the 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
}
}
I have attached the image for understanding the same:
This is function with inverted option
It will return:
'change' - string that you can use for css class in your template
'result' - plain result
'formatted' - formatted result
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 );
}
I think this covers this formula sufficiently,
((curr value - base value) / (curr value)) * 100%
Basically we just (in programming):
perform the calculation if both numbers are not 0.
If curr value is 0 then we return -100 % difference from the base,
if both are 0 then return 0 (we can't divide by 0)
Powershell example:
Strip any non numeric from vars and perform calculation
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
}