Commercial round with comma and point - php

I have used this code :
$result = number_format(round(15.5, 1), 2);
Written in my old post :
PHP - Commercial round
I have now problems with the values like : 1,597.30
I get the price as 1.00
How can I do to get the make the round and get the good price format with the prices that have number with thousands.

Never store a formatted number.
Always store it in its original format: 1597.30 This is the only format that works for calculations and formatting.
Use number_format() only for outputting the number.

You could solve this issue using the following code:
$price = '1,597.30';
$new_price = floatval(str_replace(',', '', $price));
$result = number_format(round($new_price, 1), 2);

Remove comma and all other formating (except the dot) from your numbers, otherwise comma will be used as decimal separator.

Related

Inconsistent createFromFormat return (PHP)

This works (note the single digit ".3")
$date = DateTime::createFromFormat("*-*-*.*.*-Y-m-d-H?i.*", "backup-bla-3.3.3-2019-08-23-21h16.7z");
This fails (note the double digit ".33" :
$date = DateTime::createFromFormat("*-*-*.*.*-Y-m-d-H?i.*", "backup-bla-3.3.33-2019-08-23-21h16.7z");
This makes no sense to me. Why doesn't the * succeed in this case ?
The following also works on this specific example but I cannot make use of it as the version numbers may have double digits.
$date = DateTime::createFromFormat("*-*-*.*.??-Y-m-d-H?i.*", "backup-bla-3.3.33-2019-08-23-21h16.7z");
Why it fails when using * is clear from the manual:
Random bytes until the next separator or digit
You have two digits in a row 3 and 3 so when it reaches the second 3 your provided format is incorrect and causes an error.
The inverse is true with ** and ?? because when you have a single digit number there is no second character for the second * and ? to match.
I don't see any way around this using the available format characters. Your solution seems to be modifying that value to remove anything before the year and then using Datetime:createFromFormat().
$parts = preg_split('/(?=\d{4})/', 'backup-bla-3.3.3-2019-08-23-21h16.7z', -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
$date = DateTime::createFromFormat("Y-m-d-H?i.*", $parts[1]);
echo $date->format('c');
Demo

PHP: strings automatically converted to float and gives negative numbers

I have a PHP code that will compute the balance of the quantity but it gives me a negative value as a balance quantity as shown in the image below.
I tried to check the quantities if what's causing the problem and try to var_dump the quantity. after checking using var_dump, it shows that the data type of my quantity is string while my balance quantity is float.
so far, I have my code below:
$query_po_quantity = mysqli_query($new_conn, "SELECT quantity, po_number FROM purchase_order WHERE supplier_name = '$supplier_name' AND category_name = '$category_name' AND activity = '$activity' AND description = '$description'");
$row = mysqli_fetch_assoc($query_po_quantity);
$po_quantity = $row['quantity'];
$po_number = $row['po_number'];
$query_rr_quantity = mysqli_query($new_conn, "SELECT SUM(total_received) AS quantity FROM receiving_reports WHERE po_number = '$po_number' AND category_name = '$category_name' AND activity = '$activity' AND description = '$description'");
$row = mysqli_fetch_assoc($query_rr_quantity);
$rr_quantity = $row['quantity'];
$balance = $po_quantity - $rr_quantity;
$supplier_name = preg_replace('/\\\\/', '', $supplier_name);
echo $po_quantity.' - '.$rr_quantity.' = '.$balance.'<br />';
This is the output:
how can I get the actual balance?
The reason you're getting an incorrect result when calculating 0.42 - 0.420000000000000000004 is due to errors with floating point precision. This is due to the way floating point numbers are stored, and both MySQL and PHP are susceptible to floating point errors if done incorrectly, but they also both have ways to prevent them when you do need highly precise calculations. With floating point types only the approximate value is stored and attempts to treat them as exact values in comparisons may lead to problems.
For PHP, this means you need to use either the arbitrary precision math functions or gmp functions. For MySQL, you need to be storing the numbers using the DECIMAL format with the desired precision you require.
First thing's first, you need to change the data type of your column in MySQL to DECIMAL, not a string. Strings are inappropriate to store numbers. Even if you were using a FLOAT or DOUBLE to store your values
your code may have actually worked, because these values likely would have been rounded.
Next, seeing as the value 0.420000000000000000004 came from a string stored in your database, I'm assuming the error stems from whatever calculations you did using PHP beforehand when you were calculating the value to be inserted. You will need to update this code to use precise math.
Use number_format:
$rr_quantity = number_format($row['quantity'], 2);
Float variable range 1.7E-308 and 1.7E+308 so it's give 15 digits of accuracy. Use number format

Change format of money Postgresql

I have a Postgre DB and one of these values are money (type, ofc).
When I do the Select using PHP, the output of that query is in this format:
Example: €1,00
I'm looking for something to change this format to this other:
Example: 1,00€.
What can I change in my query to get last one result?
Thanks!
Fastest way in PHP is to use str_replace :)
$cash = '€1,00';
$cash = str_replace('€','',$cash) . '€';
echo $cash;
But a better option is to change your DB field type to some numeric type and just to add the ' €' sign where you want it..
You may do this replace inside your DB SELECT statement but I think that its better to do that inside your PHP..
If its stored in database just like a number without currency you could just use function number_format($x,y,'.','')
where
$x is your number
y is number of numbers behind decimal separator
'.' - means decimal separator is .
'' -means there is no separator between thousands
so u just format your number in a way u want and add "euro" sign.
if its price there is a function called money format :
u must use it with locales of country the currency u want fe. :
setlocale(LC_MONETARY, 'de_DE');
echo money_format('%.2n', $your_variable);
this means u use currency of germany. '%.2n' means your output is from $yourvariable and have 2 decimalnumbers
And to the thing of 'euro' sign after or before number. It depends of locales. I think slovak or spanish has euro sign after number.
Try it.
This should provide you what you need, and be flexible across all currencies:
$value = '$4265';
if (!is_numeric($value[0])) {
$value = substr($value, 1) . $value[0];
}

Number format column type & calculate in PHP

I would like to insert this type of number format in to my database.
$value = "20.000,00";
I tried with FLOAT and DOUBLE, but they can't handle this. Only option left that I know which works is VARCHAR?
Although if I do this when I am working with the numbers later and tries to subtract number from each other:
$value2 = "15.933,50";
$calc = $value - $value2;
$calc is now 4.067, it should be 4.066,50 - how can this be correct?
For financial numbers, you should use the DECIMAL type. It has a fixed precision and isn't subject to the rounding problems of floating point numbers.
Never store a money number in a VARCHAR or a FLOAT.
If you want to introduce in the database your $value, you must parse it so that you can introduce the number :
$fmt = new NumberFormatter( 'da_DK', NumberFormatter::DECIMAL );
$num = $fmt->parse($value, NumberFormatter::TYPE_INT32)
To display a number you got from your DB as "20.000,00", you may use
$display_value = $fmt->format($num);
EDIT :
If you can't use a NumberFormatter, you may use this to build a string that you can introduce in a DECIMAL field (in a float one too but don't) :
$v = str_replace(',', '.', str_replace('.', '', $value));
This changes "20.000,00" to "20000.00" which the database can understand.
But it's always dangerous to ask a database to parse the strings as numbers (you may change the locale later). I'd recommend you to parse the number in PHP and to explicitly specify the locale.

How to store European Currency in MySQL?

On a new project I work on I have data in CSV format to import into a mysql table. One of the columns is a price field which stores currency in the european format ie. 345,83.
The isssue I have is storing this decimal seperator. In most European currencies the decimal seperator is "," but when I try to insert a decimal number into a field (ex. 345,83), I get the following error: "Data truncated for column 'column_name' at row 'row #'". If I use '.' instead of ',' it works fine. Could you please help me with, how to store this format in mysql?
you can store it as a regular decimal field in the database, and format the number european style when you display it
edit: just added an example of how it might be achieved
$european_numbers = array('123.345,78', '123 456,78', ',78');
foreach($european_numbers as $number) {
echo "$number was converted to ".convert_european_to_decimal($number)."\n";
// save in database now
}
function convert_european_to_decimal($number) {
// i am sure there are better was of doing this, but this is nice and simple example
$number = str_replace('.', '', $number); // remove fullstop
$number = str_replace(' ', '', $number); // remove spaces
$number = str_replace(',', '.', $number); // change comma to fullstop
return $number;
}
Use number_format or money_format, it's pretty much what you preffer.
It's worse than you think. The number 1234.56 may be written in Europe as:
1234,56
1 234,56 (space as a group separator)
1.234,56 (dot as a group separator)
In .net the number parser can works according to a given culture, so if you know the format it does the hard work for you. I'm sure you can find a PHP equivalent, it'd save you a lot of trouble.
You could import the currency field into a VARCHAR column and then copy this column into a DECIMAL column while replacing the , by a . in all rows using MySQL string-manipulation-functions.
UPDATE <<table>>
SET <<decimal-currency-col>> = REPLACE(<<varchar-currency-col>>, ',', '.');
Some data types do not have a direct
correlation between SQL Server or
Access and MySQL. One example would be
the CURRENCY data type: MySQL does not
(yet) have a CURRENCY data type, but
creating a column with the definition
DECIMAL(19,4) serves the same purpose.
While MSSQL defaults to Unicode
character types such as nCHAR and
nVARCHAR, MySQL does not so tightly
bind character sets to field types,
instead allowing for one set of
character types which can be bound to
any number of character sets,
including Unicode.
from http://dev.mysql.com/tech-resources/articles/migrating-from-microsoft.html
You could also consider multiplying it by 100 and storing it as INT.
Before inserting the price to the DB:
$price = (int)$price*100;
After receiving price from the DB:
$price = number_format($price, 2, ',', ' ');
Try replacing the "," with "."?
$price = str_replace(",", ".", $price);

Categories