PHP - Separate a string with comma - php

I am getting value from a API to get the amound spend.
Currently I got this:
Total invested: € 17101
Total invested(formatted): € Eu 17101,00
What I want:
I want to make the total invested string (fx 17101) to a currency number (171,01).
I have tried to do it with:
number_format($jsonData->amount_spent, 2, ',')
Sadly nothing was given the result I wanted

If the input is a string '17101' in Euro-Cents devide by 100 and then do the format:
$input = "17101";
echo number_format($input/100, 2, ',', '');
// output: 171,01
Also note that
This function accepts either one, two, or four parameters (not three):
from the Docs

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 change in mysql datatype float dot to comma?

In my mysql database I have a column with float datatype and with length 10,2.
When I put the data in database in row it looks like this:
2,589.20
In my country, Serbia, visually will need to look like this:
2.589,20
(first dots, then comma).
When I use it in "value" of form (input) the number_format($number, 2, '.', ',') then I can put the $number in the database, but if it's a number_format($faktura_cenanasa, 2, ',', '.') in "value" then I can't put it in database because of a wrong format of the "value". This problem is only when I reload the data in form, when a reload it somewhere else on site it't not a problem (when I print it on screen).
number_format due to rounding can return misleading output especially for large numbers.
for instance
echo number_format( 1000000000000000000.00952, 2 );
// output: 1,000,000,000,000,000,000.00
echo number_format( 9999999999999999999.00952, 2 );
// output: 10,000,000,000,000,000,000.00
echo number_format( 999999999999999999999999999.00952, 2 );
// output: 1,000,000,000,000,000,013,287,555,072.00
Alternatively like #aynber wrote in a comment you should add one more aliased column or replace the number column with FORMAT in your query
SELECT ..., FORMAT( `number`, 2, 'de_DE' ) AS `formatted_number`
FROM ...
Before replacing the locale to Serbian (in the example is 'de_DE') you should check that it is available into Mysql Locale Support
Additionally just in case make sure that the formatted output is what you expect. There might be a case where your result will be something like the following, instead both should have the same format.
SELECT FORMAT(12500000000000.2015, 2,'de_DE'), FORMAT(12500000000000.2015, 2,'el_GR');
+----------------------------------------+----------------------------------------+
| FORMAT(12500000000000.2015, 2,'de_DE') | FORMAT(12500000000000.2015, 2,'el_GR') |
+----------------------------------------+----------------------------------------+
| 12.500.000.000.000,20 | 12500000000000,20 |
+----------------------------------------+----------------------------------------+
update
When you receive the number formatted- well not a number anymore instead a string- you will be able to edit it as you are please. But, before storing it back to the database you will need to remove all thousand separators and then change the decimal point to '.', i.e
$number = str_replace( [ '.', ',' ], ['', '.'], $number );
Finally insert and this is it.

Format number as currency

I am (learning) using PHP to select column data from MySQL into an array using this, CONCAT('$',FORMAT(price, '5')) as price and it outputs $1,751.60000 or $10.00230 or $7.23000 which is great.
However, I would like to remove the trailing zeros but still be able to have a minimum of two decimal places
$1,751.60000 = $1,751.60
$10.00230 = $10.0023
$7.23000 = $7.23
I have read a number of similar post regarding number to currency conversion but none doesn't seem to solve my problem as they remove all the trailing zeros.
We will implement this in two way.(Mysql, PHP).
MYSQL:
FORMAT('price', 2 ) This is mysql function. It takes first parameter as value & second parameter is the number of decimal places.
Syntax:
FORMAT( value, Decimal );
Example:
FORMAT('1751.60000', 2 ) => 1751.60 // Output
FORMAT('1751.60000', 3 ) => 1751.600 // Output
PHP:
In PHP we have number_format() function. This is working same as MYSQL.
Syntax:
number_format( value, Decimal );
Example:
number_format('1751.60000', 2 ) => 1751.60 // Output
number_format('1751.60000', 3 ) => 1751.600 // Output
The Best way is to implement at MYSQL.
Note: These both function round up the values.
I will post this code in PHP since it is easier for me.
$price = $row['price']; // the original price
if (number_format($price, 2) == $price) {
echo '$'.number_format($price, 2);
} else {
echo '$'.rtrim(number_format($price, 5),'0');
}
rtrim will remove any trailing character specified. In this case, remove trailing zeros.
Note : I only put this code number_format($price, 5) because of the sample of the question. If you wish to keep all decimal number minus trailing zeros, just using $price is enough.

PHP lowest common denomination

I am working on a payment gateway and the amount parameter needs to formatted this way:
amount – (digits only) the integer value of the transaction in lowest common denomination (ex. $5.20 is 520)
I have already removed the $ and all values will be rounded to 2 decimal places.
In PHP if i try to cast amount as int ie (int)$amount I am going to loose the .20 in the example though its needed. What could be the best way to go about this?
You can multiply the amount by 100 and then convert it...
$amount = (int)($amount*100);
So 5.20 becomes 520.
If you are not sure about the number of decimal places, you could use regex to strip non-digital values from your string.
echo preg_replace('~\D+~', '', $amount);
\D means any non-numeric character. + means one or more.
If the value needs to be cast as an integer (rather than a string) write(int) just before preg_replace.
Of course, you could use str_replace() and target known characters like: $ and . (and - if it may exist).
After some feedback from the OP...
You can round and format in one step with number_format().
Code: ( Demo: https://3v4l.org/ir54s )
$amounts = array(0.001, 0.005, 5.20, 5.195, 5.204, 5);
foreach ($amounts as $amount) {
echo $amount , "->" , (int)number_format($amount, 2, '', '')."\n";
}
Output:
0.001->0
0.005->1
5.2->520
5.195->520
5.204->520
5->500

echo/print starting from exact character

I don't know if it's possible but i want to achieve this:
i have lot of product id's, each one being a different variable: $p1, $p2, $p3, etc.
I'm using that variable to call images and links, so that's quite simple (the images names are the same than product id).
The structure of the names are: 1234-123 . The first sequence can be 3 or 4 numbers lenght, and the second sequence can be 2 or 3 numbers lenght.
i.e:
$p1 = '1234-123'
$p2 = '123-12'
I need to display those products ids in a certain format: Product($p1): 1234 (123)
So, my concrete question is:
How can i separate this 2 sequences? i mean, something like:
PRODUCT: <?php echo from first value to "-"?> (<?php echo from "-" to end of variable value ?>)
Use explode():
list($firstPart, $secondPart) = explode('-', $p1);

Categories