How to delete trailing zeros after the 3rd decimal place in PHP? - 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.

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

number_format() php remove trailing zeros

Is there a way with number_format() to leave out decimal places if the number is not a float/decimal?
For example, I would like the following input/output combos:
50.8 => 50.8
50.23 => 50.23
50.0 => 50
50.00 => 50
50 => 50
Is there a way to do this with just a standard number_format()?
You can add 0 to the formatted string. It will remove trailing zeros.
echo number_format(3.0, 1, ".", "") + 0; // 3
A Better Solution: The above solution fails to work for specific locales. So in that case, you can just type cast the number to float data type. Note: You might loose precision after type casting to float, bigger the number, more the chances of truncating the number.
echo (float) 3.0; // 3
Ultimate Solution: The only safe way is to use regex:
echo preg_replace("/\.?0+$/", "", 3.0); // 3
echo preg_replace("/\d+\.?\d*(\.?0+)/", "", 3.0); // 3
Snippet 1 DEMO
Snippet 2 DEMO
Snippet 3 DEMO
If you want to use whitespace here is better solution
function real_num ($num, $float)
{
if (!is_numeric($num) OR is_nan($num) ) return 0;
$r = number_format($num, $float, '.', ' ');
if (false !== strpos($r, '.'))
$r = rtrim(rtrim($r, '0'), '.');
return $r;
}
Use:
$a = 50.00;
$a = round($a, 2);
Even though the number has 2 zeros trailing it, if you round it, it won't show the decimal places, unless they have some kind of value.
So 50.00 rounded using 2 places will be 50, BUT 50.23 will be 50.23.
Unless you specify at which point to round up or down, it won't change your decimal values. So just use default round()

Php ignores decimals while adding two numbers

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.

How to Present a floating point number using php

I have a price database that stores numbers as floating point. These are presented on a website. Prices can be in the format.
x.x (e.g. 1.4)
x.xx (e.g. 1.99)
x.xxx (e.g. 1.299) <-- new price format
I used to use the string format or %.2f to standardize the prices to two decimal places but now I need to show 3 as well but only if the price is 3 decimal place long.
e.g. 1.4 would display 1.40
1.45 would display 1.45
1.445 would display 1.445
The above formats would be the desired output for the given input.
using %.3f shows all with 3 digits.
e.g. 1.4 would display 1.400
1.45 would display 1.450
1.445 would display 1.445
But that is not what i want does anyone know the best way to do the following.
i.e. any number should display 2 decimal places if it has 0 1 or 2 decimal places
if it has 3 or more decimal places it should display 3 decimal places
I would just format it to three places, then trim a final 0.
$formatted = number_format($value, 3, ".", "");
if (substr($formatted, -1) === "0") $formatted = substr($formatted, 0, -1);
Use this dude
number_format($data->price, 0, ',', '.');
http://php.net/manual/en/function.number-format.php
Here is what I did due to the need to cope with some special cases I had in the app.
count the number of dec places ($prices is a float from the database).
format based on the count in the places using a switch statement.
For all cases with less than 3 decimal places format with 2 (except zero)
For all other case format with 3.
$decimals = strlen(substr(strrchr($price,"."),1));
switch ($decimals) {
case 0: {
if ($price != 0) {
$price = number_format($price),2);
}
break;
}
case 1: {
$price = number_format($price),2);
break;
}
case 2: {
$price = number_format($price),2);
break;
}
default: {
$price = number_format($price),3); // three dec places all other prices
break;
}
}
Thanks for the help...

Make dots between numbers in php

I would like to make dots between my total value.
If i have 425000 i would like it to show as 425.000
Is there a function in php that implodes dots for numbers or how can i do this then?
Use number_format for this:
$number = 425000;
echo number_format( $number, 0, '', '.' );
The above example means: format the number, using 0 decimal places, an empty string as the decimal point (as we're not using decimal places anyway), and use . as the thousands separator.
Unless of course I misunderstood your intent, and you want to format the number as a number with 3 decimal places:
$number = 425000;
echo number_format( $number, 3, '.', '' );
The above example means: format the number, using 3 decimal places, . as the decimal point (default), and an empty string as the thousands separator (defaults to ,).
If the default thousands separator is good enough for you, you can just use 1:
$number = 425000;
echo number_format( $number, 3 );
1) Mind you: number_format accepts either 1, 2 or 4 parameters, not 3.
I guess you're looking for the number_format function.

Categories