Displaying currency values greater than 1000 - php

I'm trying to modify a pseudo-shopping cart (it's array based storing values in user meta and not database) PHP file that wrongly displays currency > 1000 as 0.01
Here's the block I want to change:
public function get_cart_value()
{
$cart = $this->cart;
$prices = array();
$cart = apply_filters('ss_mod_cart_value', $cart);
foreach ($cart['products'] as $product)
{
array_push( $prices, array('price'=>trim($product['price']), 'discount' => trim($product['discount'] )));
}
$total = 0;
foreach($prices as $price)
{
$price = $this->calc_discount($price['price'], $price['discount']);
$price = str_replace('.', '', $price['final_price']);
$total += $price;
}
$total = number_format($total/100, 2);
return $total;
}
The cart button it works on will correctly display the total values of items less than 4 digits, for example:
300 + 500 = 800
but
300 + 500 + 1000 = 800.01 instead of 1,800
I've been trying to change number_format() to make it work but cannot find a solution.

I think by this line
$price = str_replace('.', '', $price['final_price']);
300+500+ "1000";
your numbers like 1,000 are converted to a string and then your total becomes 801.
you have to convert to float in proper way as suggested in this
PHP: unformat money

Related

PHP ceil calculation differs in result from manually calculated result

I have this script:
function round_price_with_limits( $price = null, $multiplier = 9.3, $nearest = 10, $minus = 0.05, $map = 9.95, $msrp = 9999999999) {
// Ensure a price was provided.
if ( !empty( $price ) ) {
// Calculate price with markup and round it.
$rounded_price = ( ceil ( ( $price * $multiplier ) / $nearest ) * $nearest ) - $minus;
// If price is less than minimum, return minimum.
if($rounded_price < $map){
return $map;
}
// If price is greater than maximum, return maximum.
elseif($rounded_price > $msrp){
return $msrp;
} else {
// Return price otherwise.
return $rounded_price;
}
}
}
It works on almost all products, except for one with $price value = 1,76.
The end result when running the script becommes 9.95
When I calculate by hand, the result is 19.95
Can you spot why this is calculated differently via the php?

Loop to Calculate Price

trying to create a loop to calculate a price but cant get my head around how to do it.
$sell = ($price*$vat);
$profit = ((($price*$vat)*0.04)+0.2);
function newSell($price1){
$price1 = $price1 + 0.10;
return $price;
}
do {
$price1 = newSell($price);
$profit = ((($price1*$vat)*0.04)+0.2);
} while ($profit < 0);
$price is the price of my item
$sell is my starting price.
$profit is the calcualtion to work out my profit.
What i want to do is look around and if my profit is less than 0 i want to add 10p (0.10) to my price and then recalculate my profit and evaluate it again. Want to keep going until my profit is above 1 at which point it stops and my new selling price has been set.
Cant for the life of me get my head around this!
Many thanks
First of all your newSell function should look like this:
function newSell($price) {
return $price + .1
}
It currently does nothing.
Second, are you sure this is the way you should be trying to solve this? It seems to me like you are just trying to solve for $profit >= 1. It's a simple equation that takes no loops whatsoever.
Apparently $profit = $price * $vat * .04 + .2, so you are really looking at 1 <= $price * $vat * .04 + .2 or 20 / $vat <= $price
So if $price >= 20 / $vat then $profit >= 1.
To do specifically what you asked:
do {
$profit = $price * $vat * .04 + .2;
$price = $price + .1;
} while ($profit < 1);

PHP calculate percentages

I need some help. It's a simple code, but I don't have idea how to write in down. I have the numbers:
$NumberOne = 500;
$NumberTwo = 430;
$NumberThree = 150;
$NumberFour = 30;
At all this is:
$Everything = 1110; // all added
Now I want to show what percentage is for example $NumberFour of everything or what percentage is $NumberTwo of $Everything. So the "market share".
Use some simple maths: divide the number you wish to find the percentage for by the total and multiply by 100.
Example:
$total = 250;
$portion = 50;
$percentage = ($portion / $total) * 100; // 20
Solution to original example
To get $NumberFour as a percentage of the total amount you'd use:
$percentage = ($NumberFour / $Everything) * 100;
Rounding
Depending on the numbers you're working with, you may want to round the resulting percentage. In my initial example, we get 20% which is a nice round number. The original question however uses 1110 as the total and 30 as the number to calculate the percentage for (2.70270...).
PHP's built in round() function could be useful when working with percentages for display: https://www.php.net/manual/en/function.round.php
echo round($percentage, 2) . '%'; // 2.7% -- (30 / 1110) * 100 rounded to 2dp
Helper Functions
I would only contemplate creating helper functions when their use justifies it (if calculating and displaying a percentage isn't a one-off). I've attached an example below tying together everything from above.
function format_percentage($percentage, $precision = 2) {
return round($percentage, $precision) . '%';
}
function calculate_percentage($number, $total) {
// Can't divide by zero so let's catch that early.
if ($total == 0) {
return 0;
}
return ($number / $total) * 100;
}
function calculate_percentage_for_display($number, $total) {
return format_percentage(calculate_percentage($number, $total));
}
echo calculate_percentage_for_display(50, 250); // 20%
echo calculate_percentage_for_display(30, 1110); // 2.7%
echo calculate_percentage_for_display(75, 190); // 39.47%
Create function to calculate percentage between two numbers.
<?php
/**
* Calculate percetage between the numbers
*/
function percentageOf( $number, $everything, $decimals = 2 ){
return round( $number / $everything * 100, $decimals );
}
$numbers = array( 500, 430, 150, 30 );
$everything = array_sum( $numbers );
echo 'First of everything: '.percentageOf( $numbers[0], $everything )."%\n";
echo 'Second of everything: '.percentageOf( $numbers[1], $everything )."%\n";
echo 'Third of everything: '.percentageOf( $numbers[2], $everything )."%\n";
echo 'Fourth of everything: '.percentageOf( $numbers[3], $everything )."%\n";
?>
This outputs
First of everything: 45.05%
Second of everything: 38.74%
Third of everything: 13.51%
Fourth of everything: 2.7%
You can also come up with the percentage with the following formula. For the percentage, add a 0. in front of it. So 5% would be 0.05. Total X 0.05 is the amount.

Wrong percentage with PHP

$rewards = Reward::where('m_id', $module->id)->count();
$percentage = 0;
if($rewards != 0)
{
$count1 = $rewards / 100;
$count2 = $count1 * $users;
$count3 = 100 - $count2;
echo $count3;
}
$rest = 100 - $percentage;
$new = array(
'name' => $module->name,
'percentage' => $percentage,
'rest' => $rest
);
Hey,
this code above is a simple function to get percentage and then return a view with it.
The problem im having is that the $users are 569 right now and the reward is 1 so the correct percentage would be 0.569% out of 100%. But my code is return 5.69% out of 100%.
I have been searching around and i really can't find any way for noticing if this number should be with a zero or not! right now it should be 0.569% but i can't really just add a zero to it in the start as you can see.
Any solutions how to noticing if the number is only decimals or not ?
If reward is equal to one than according to your calculation count1=0.01 and count2= 5.69 .percentage calculates correctly .

Deducting 25% from more than one item in loop

I wonder if someone could please help me out a little. I have a loop that loops through the contents of a shopping cart. I wish to apply a 25% discount to additional items purchased. So basically 1st item is full price and every other item is reduced by 25%. I've tried various methods but all i seem to get is the discount apply to all or nothing.
The loop below works perfectly if i remove the if statement and its contents thus not wishing to apply a discount. As it currently stands it does not add a discount at all. If i remove the if condition and use it's contents then it will apply a 25% discount to all items.
for($Loop = 0; $Loop < count($Cart); $Loop++)
{
$Total += $ShoppingCart[$Loop][Price];
if($Loop > 1) {
$Total += $ShoppingCart[$Loop][Price];
$PercentageAmount = 25;
$TotalPrice = $TotalPrice * ((100-$PercentageAmount) / 100);
}
}
Edited:
Unfortunately none of the answers, although maybe technically good, do not fix my problem. I have had to result to placing 2 if statements within a loop and then calculating their combined total. Not an ideal solution but works perfectly never the less. Somehow i need the sort it so then the most expensive item is at full price. It would be much easier if i was not tied to using a loop in this fashion and instead could use array functions.
$i = 0;
for($Loop = 0; $Loop < count($Cart); $Loop++)
{
if($i == 0) {
$Total += $ShoppingCart[$Loop][Price];
}
if($i > 0) {
$TotalMulti += $ShoppingCart[$Loop][Price];
$TotalMulti = $TotalMulti * .75;
}
$i++;
}
$NewTotal = $Total + $TotalMulti;
Here's how I would do it:
$prices = array_column($ShoppingCart, 'Price');
array_walk($prices, function(&$price, $i) { if($i) $price *= .75; });
$total = array_sum($prices);
How it works:
The prices are pulled out in their own array -- I much prefer this because the discount code does not mess with the "normal" prices, which might cause unexpected complications.
The array of prices is iterated over, and every element but the first is set to 75% of its value.
The total price is just the sum of the discounted prices.
This code depends on array_column, which is only available starting with PHP 5.5. For earlier versions you can either grab an implementation from here or substitute this:
$prices = array_map(function($el) { return $el['Price']; }, $ShoppingCart);
If the discount percentage is a variable you will also need this modification:
$discount = .25;
array_walk(
$prices,
function(&$price, $i) use($discount) { if($i) $price *= (1 - $discount); }
);
for($Loop = 0; $Loop < count($Cart); $Loop++){
if($Loop > 0) {
$Total += ($Cart[$Loop]['Price']*0.75);
} else {
$Total += $Cart[$Loop]['Price'];
}
}
Hope this helps:
for($Loop = 0; $Loop < count($Cart); $Loop++)
{
# if not first item then discount price
if($Loop > 1) {
$PercentageAmount = 25;
# grab the price
$itemPrice = $ShoppingCart[$Loop][Price];
# what should the user pay?
$itemDiscountPrice = $itemPrice * (100.0 - $PercentageAmount) / 100.0
# add it to total
$Total += $itemDiscountPrice;
} else {
# if first item -> full price
$Total += $ShoppingCart[$Loop][Price];
}
}

Categories