Php ignores decimals while adding two numbers - php

When adding two number it ignores the decimals, in database the product_price and product_shipping_cost data type is decimal(10,2)
$product_price = 272.70; $product_price = 189.00;
$product_shipping_cost 14.00;
The total should be 475.70 but i get 475.7 as the output how do i fix this i have tried adding (float) but still same
foreach($mycart as $row_checker){
$CKItemSubtotal += (float)(($row_checker->product_discount>0) ? $row_checker->product_price * ((100-$row_checker->product_discount) / 100) * $row_checker->cart_qty : $row_checker->product_price * $row_checker->cart_qty) + $row_checker->product_shipping_cost;
}
Please can anyone help me

number_format($number, 2)
If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.

You may also format number using printf. In your case: printf('%.2f', 475.7);, but that's up to you.

Related

How to correctly do maths with higher numbers in PHP

I am trying to display the total amount which is product price times quantity.
This works perfectly for numbers under 1000, but above that a dot is added and my script breaks. How can I fix that?
I have these numbers:
150,00
1.200,00
They are looped with variable $price.
I then replace all commas for dots like this:
$subtotalreken = str_replace(',','.',$price);
$subtotalreken then contains:
150.00
1.200.00
I then multiply this with the quantity amount like this:
$totalfinal = $subtotalreken * $cart['quantity'];
The quantity is 2 for both products, and if I echo $totalfinal, this is my result:
300
2.4
Why is it 2.4? And not 2.400?
I need the european/dutch format, so dots for every three numbers and cents after the comma. How can I do that?
Assuming that the "number" uses comma as decimal and dots as thousands separator: remove all dots and replace the comma with dot so that 1.234,56 becomes 1234.56:
$value = (float) strtr("1.234,56", ["." => "", "," => "."]); // 1234.56
You can format the value again using number_format:
echo number_format($value, 2, ",", "."); // 1.234,56
Before calculations remove any formatting from your number (just make sure you always have 2 decimal places number):
$number = preg_replace('/[^\d]/', '', $input);
Then do your calculations (number is in cents) and show to user formatted number:
echo number_format($number * $qunatity / 100, '.', ',', 2);

How to show decimal value after multiplication

I have value which stored in database like price. 123.00
When i tried to see the subtotal which is quantity * price.
So 123.00*1 = 123.00
But in view it shows 123 instead of 123.00 where price showing like 123.00 in same table.
How can i show decimal value after multiplication?
You need to format the number using number format PHP function. Consider
$price = 125;
$quantity = 1;
echo number_format($quantity*$price,2);
You can also have extra comma separated values that set the decimal separator, i.e. "." and the thousands separator also i.e. ",". See http://php.net/manual/en/function.number-format.php

PHP Number Formatting

I have been trying all morning but how would I this number 1304583496 to look like this
13.04583496
and the same goes for this number
456604223 to 4.56604223
There are always 8 numbers to the right.
Divide it with 100000000, or use "pow" function:
$number / pow(10, 8);
You could also use the official number_format method after division to keep your ending zeroes and have your number displayed in a nice manner.
<?php
$num = 1304583496; //the number
echo number_format($num/100000000,8,"."," "); //number of decimals = 8, comma seperator is . and thousands seperator is a space here
?>
For more information on this function: http://www.w3schools.com/php/func_string_number_format.asp

How to delete trailing zeros after the 3rd decimal place in PHP?

thanks in advance.
I have a WP WooCommerce store and need to upload some prices that have 3 decimal places, e.g. £0.012 (products that are purchased in volumes of 000s).
The majority of my products are 'ordinary' with 2 decimal places.
There is a function in WooCommerce that allows for 3 decimal places - fine. Also a function to delete trailing zeros, but it deletes them if it's an integer e.g. £10.00 becomes £10.
My problem arises when the 95% of 'ordinary' price products start showing £10.000 or £5.230.
In a nutshell I'm looking for a way to delete trailing zeros but ONLY after the 3 decimal place;
Retain - £0.012
Delete any 3rd decimal 0 on prices like £10.00 or £5.23
Does anyone have a good solution?
Thanks
If you want to use regular expressions you can match them with
(?<=\d{2})(0+)$
preg_replace("/(?<=\d{2})(0+)$/", "", $price_string)
to match all zeroes which come after at least two digits. (It will match the zeroes in parenthesis):
12.002(0)
12.00(0000)
12.01(000000)
12.232(0)
12.123
an if else statement would probably work, unless you also have prices like 10.001:
$price = '0.001';
if ($price < 1) {
// don't round
} else {
$price = number_format($price, 2);
}
or just
$price = ( $price < 1 ) ? $price : number_format($price, 2) ;
Why not just something like this ↓ ?
$numberAsString = number_format($yourUglyNumber, 2, '.', ' ');
PHP function number_format
If you get the number as string with the money sign, you can first filter this out:
$moneyString = "£300.4578525";
// remove all non-numeric and cast to number
$moneyNum = preg_replace("/[^0-9.]/", "", $moneyString) + 0;
// format
$formatted = number_format($moneyNum, 2, '.', ' ');
// add the money symbol if you want
$formatted = '£' + $formatted.

Calculating total price from string value in php

I have a e-commerce shop and on the shopping cart page it gives me a separate price for every product, but I need total price.
in order to do that, I need to calculate all these values together and that's fine.
But, what bugs me is that I should calculate the sum of variables that are given in this format:
$455.00
What is the best way to extract the value "455" so I could add it to another value afterwards?
I hope I made myself clear...
Don't use float, but instead use an integer in cent. Floats are not precise (see Floating Point Precision), so the calculation tend to fail if you use floats. That's especially a burden if it is related to payments.
$str = '$455.00';
$r = sscanf($str, '$%d.%d', $dollar, $cent);
if ($r <> 2 or $cent > 99 or $cent < 0 or $dollar > 9999 or $dollar < 0) throw new Exception(sprintf('Invalid string "%s"', $str));
$amountInDollarCents = $dollar * 100 + $cent;
echo $str, ' -> ', $amountInDollarCents;
Demo
If you need only the dollar sign removed, use str_replace. To convert that to int or float, typecast it. However, using float results in non-exact calculations so be careful with it!
$newval = (int)str_replace('$', '', '$455.00');
I think that your ECommerce site only has $ (USD)
$price= substr($string_price,1);
This will convert your string to a float:
$price = (float)substr("$455.00", 1);
echo($price);
For more information, you can see this answer, which has a couple of good links for you in it.
What about the following:
$amount = array();
$amount[0] = '$455.15';
$amount[2] = '$85.75';
$total = 0;
foreach ($amount AS $value) {
$value = str_replace('$', '', $value);
$total += $value;
}
echo $total . "\n";
The cleaning operation is:
$value = str_replace('$', '', $value);
You might want to extract it in a function, especially if you need to use it in more than one place.
Another thing to think about is, why do you have the value in such way? It's a display format and such conversion should be the last to be done, ideally by the template. Maybe, if possible, you should consider to fix the code before, instead of applying a patch like this one.
It really looks like your program is doing it wrong. You should really represent all prices as (double) instead of a string. Then only when you need to show the price to the user you would prepend the $ sign to it, converting it to a string. But your program should really treat prices as numbers and not strings.
If you storing your price in the database as a string "$5.99" then you are really doing it wrong.
It's been a long time since I worked with PHP, so I don't know what the best practice would be for working with currency. One quick method would be to remove "$" and ".", and just add together the resulting as integers.
use str_replace() for instance, and replace "$" and "." with an empty string: http://se2.php.net/manual/en/function.str-replace.php
This will give you the whole sum in cents (thus avoiding some potential rounding problems). You can then divide it by 100 and format it however you like to display the sum as dollars.

Categories