Calculate percentage saved between two numbers? - math

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
}

Related

PHP Recursion Script is taking took long to execute HackerRank powerSum problem

Time limit exceeded
Your code did not execute within the time limits. Please optimize your code.
<?php
/*
* Complete the 'powerSum' function below.
*
* The function is expected to return an INTEGER.
* The function accepts following parameters:
* 1. INTEGER X
* 2. INTEGER N
*/
function powerSum($X, $N) {
// Write your code here
if (1 <= $X && $X <= 1000 && 2 <= $N && $N <= 10) {
$num = 1;
$list = [];
while ( true ) {
$pow = pow($num, $N);
if ($pow > $X) {break;}
$list[] = $pow;
$num ++;
}
$limit = $X;
$array = $list;
// the algorithm is usable if the number of elements is less than 20 (because set_time_limit)
$num = count($array);
//The total number of possible combinations
$total = pow($N, $num);
$out = array();
// loop through each possible combination
for ($i = 0; $i < $total; $i++) {
$comb = array();
// for each combination check if each bit is set
for ($j = 0; $j < $num; $j++) {
// is bit $j set in $i?
if (pow($N, $j) & $i){
$comb[] = $array[$j];
}
}
if (array_sum($comb) == $limit)
{
$out[] = $comb;
}
}
array_multisort(array_map('count', $out), SORT_ASC, $out);
$out = array_unique($out, SORT_REGULAR);
return count($out);
}
}
The above function is working and passing a lot of test cases but fails only due to timeout reasons.
I hope someone will help me fix this problem as soon as possible.
I ran the code on HackerRank, it ran well but failed on test case due to time.
The link to this challenge on hackerRank is:https://www.hackerrank.com/challenges/the-power-sum/problem?isFullScreen=true

Convert thousand to K, million to M in woocommerce

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;
?>

WooCommerce - Multiple cart dicounts

I want a cart discount based on the total
5% over $600 order and 10% over $1000?
I can get it to work for the over $600 but not the over $1000. I get an error on line 15.
add_action( 'woocommerce_before_cart', 'apply_matched_coupons' );
function apply_matched_coupons() {
global $woocommerce;
$coupon_code = 'over600'; // your coupon code here
$coupon_codeb = 'over1000'; // your coupon code here
if ( $woocommerce->cart->has_discount( $coupon_code ) ) return;
if ( $woocommerce->cart->cart_contents_total >= 600 ) {
$woocommerce->cart->add_discount( $coupon_code );
$woocommerce->show_messages();
}
if ( $woocommerce->cart->cart_contents_total >= 1000 ) {
$woocommerce->cart->add_discount( $coupon_codeb );
$woocommerce->show_messages();
}
}
Ended up doing it a completely different way
function nh_custom_coupon_filter() {
global $woocommerce;
$excluded_amount = $discount_percent = 0;
$working_total = $woocommerce->cart->cart_contents_total;
$excluded_categories = array(
217, # Training
223, # Starter Kits
);
# Only apply manual discount if no coupons are applied
if (!$woocommerce->cart->applied_coupons) {
# Find any items in cart that belong to the restricted categories
foreach ($woocommerce->cart->cart_contents as $item) {
$product_categories = get_the_terms($item['product_id'], 'product_cat');
if (empty($product_categories) || is_wp_error($product_categories) || !$product_categories) {
if (is_wp_error($product_categories)) {
wp_die($product_categories->get_error_message());
}
else {
$product_categories = new WP_Error('no_product_categories', "The product \"".$item->post_title."\" doesn't have any categories attached, thus no discounts can be calculated.", "Fatal Error");
wp_die($product_categories);
}
}
foreach ($excluded_categories as $excluded_category) {
foreach ($product_categories as $category) {
if ($excluded_category == $category->term_id) {
$excluded_amount += $item['line_subtotal']; # Increase our exclusion amount
$working_total -= $item['line_subtotal']; # Decrease our discountable amount
}
}
}
}
# Logic to determine WHICH discount to apply based on subtotal
if ($working_total >= 600 && $working_total < 1000) {
$discount_percent = 5;
}
elseif ($working_total >= 1000) {
$discount_percent = 10;
}
else {
$discount_percent = 0;
}
# Make sure cart total is eligible for discount
if ($discount_percent > 0) {
$discount_amount = ( ( ($discount_percent/100) * $working_total ) * -1 );
$woocommerce->cart->add_fee('Bulk Discount', $discount_amount);
}
}
}
add_action('woocommerce_cart_calculate_fees', 'nh_custom_coupon_filter');

Need assistance with recursion in JS

I'm having a great deal of trouble wrapping my head around recursion. Simple recursion I can do but this is one is not easy for me. My goal here is to speed up this search algorithm. I'm guessing recursion will help. It takes 15 seconds on a simple 43 node tree with children as it is. Below is my unrolled recursion fomr of the code that works.
var nodeList = new Array();
var removeList = new Array();
var count = 0;
var foundInThisNodeTree;
var find = function ( condition )
{
}
while ( this.treeIDMap.igTree( "nodeByPath", count ).data() )
{
var foundInThisNodeTree = false;
var n;
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count ) )
if ( n.data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; }
else {//look deeper
var i = 0;
while ( this.treeIDMap.igTree( "nodeByPath", count + "_" + i ).data() )
{
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count + "_" + i ) );
if ( n.data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
else {//look deeper
var j = 0;
while ( this.treeIDMap.igTree( "nodeByPath", count + "_" + i + "_" + j ).data() )
{
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count + "_" + i + "_" + j ) );
if ( n.data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
else {//look deeper
var k = 0;
while ( this.treeIDMap.igTree( "nodeByPath", count + "_" + i + "_" + j + "_" + k ).data() )
{
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count + "_" + i + "_" + j + "_" + k ) );
if ( n.data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
k++;
}
}
j++;
}
}
i++;
}
}
if ( !foundInThisNodeTree ) this.treeIDMap.igTree("removeAt", ""+count )
else count++;
}
*** second revision suggested by Mirco Ellmann *****
var nodeList = new Array();
var removeList = new Array();
var count = 0;
var foundInThisNodeTree;
filter = filter.toLowerCase();
while ( this.treeIDMap.igTree( "nodeByPath", count ).data() )
{
var foundInThisNodeTree = false;
var n;
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count ) )
if ( n.data.ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; }
else {//look deeper
var i = 0;
n = this.treeIDMap.igTree( "childrenByPath", count );
while ( n[i] )
{
if ( n[i].data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
var j = 0;
n = this.treeIDMap.igTree( "childrenByPath", count + "_" + i );
while ( n[j] )
{
if ( n[j].data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
var k = 0;
n = this.treeIDMap.igTree( "childrenByPath", count + "_" + i + "_" + j);
while ( n[k] )
{
if ( n[k].data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
k++;
}
j++;
}
i++;
}
}
if ( !foundInThisNodeTree ) this.treeIDMap.igTree("removeAt", ""+count )
else count++;
}
****using my branchable trees to get the data no need for any calls to tree****
var count = 0;
var foundInThisNodeTree;
filter = filter.toLowerCase();
while ( this.treeIDMap.igTree( "nodeByPath", count ).data() )
{
var foundInThisNodeTree = false;
var n;
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count ) )
if ( n.data.ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; }
if ( n.data.branch )//look at all childer under the root node
{
var i = 0;
n = n.data.branch;
while ( n[i] )//look at all childer under the root node
{
if ( n[i].ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
while ( n[i].branch )//look deeper
{
var j = 0;
n = n[i].branch;
if ( n[j].ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
while ( n[j].branch )//look deeper
{
var k = 0;
n = n[j].branch;
if ( n[k].ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
k++;
}
j++;
}
i++;
}
}
if ( !foundInThisNodeTree ) this.treeIDMap.igTree("removeAt", ""+count )
else count++;
}
instead of always use "nodeByPath" you should use "childrenByPath".
that would minimize the search calls on the igTree.
PS: USE not REPLACE ;)
You're not really doing this recursively. You're rather repeating your code for each level in the hierarchy. What you want is a helper function which takes the current node-path as a parameter and recursively calls the same method for each of its children with their id added to the path of the current node. Recursively means the code should work for any depth of tree. To me it looks like your code will only work for a set depth.
For the speed issue, there might be two issues. I didn't really read your code too closely, so I leave it to you to figure out which one is more likely.
You might be revisiting nodes. If so, obviously that would impact performance.
The framework you're using might be slow with looking up the nodes. One solution could be to find alternate methods to call on the framework which is meant for what you're doing. For instance the framework might have a hierarchical representation internally, but has to rebuild it or parse it when you pass in your full paths. Look for methods taking a source and relative path instead. If that's not the problem the framework might just be slow, and you might be better of to read all the nodes and build your own in-memory tree to use instead.
ok, I found a way to use the data provider and use a normal Json search. Still if anyone can speed this up I'd be grateful. I just when from 15 seconds to 1. This one has the recursion I need.
findInObject = function( obj, prop, val )
{
if ( obj !== null && obj.hasOwnProperty( prop ) && obj[prop].toLowerCase().indexOf(val) > -1 )
{
return obj;
} else
{
for ( var s in obj )
{
if ( obj.hasOwnProperty( s ) && typeof obj[s] == 'object' && obj[s] !== null )
{
var result = findInObject( obj[s], prop, val );
if ( result !== null )
{
return result;
}
}
}
}
return null;
}
for ( var i = 0; i < this.treeData.length; i++)
{
if ( findInObject( this.treeData[i], "ITEM", filter ) ) foundNodes.push( this.treeData[i] )//does the node have a match?
}
this.treeIDMap.igTree( { dataSource: foundNodes } );
this.treeIDMap.igTree( "dataBind" );
};

Formula for percentage

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 . '%';
}

Resources