How to store European Currency in MySQL? - php

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

Related

Display BigInt DataType of length 10 in Excel Sheet using PHP

I want to make a excel file by fetching data from database. Every thing works fine but the phone number field return unknown value in excel sheet but it displays correct value in browser.
<?php
include('connection.php');
header( "Content-Type: application/vnd.ms-excel" );
header( "Content-disposition: attachment; filename=spreadsheet.xls" );
$q = mysql_query("select * from members order by id desc");
echo 'First Name' . "\t" . 'email' . "\t" . 'Phone' . "\t". 'address' . "\t". 'Membership Number' . "\t". 'Membership Category' . "\n";
while($r = mysql_fetch_array($q))
{
$name = $r['name'];
$email = $r['email'];
$phone = $r['phone'];
$address = $r['address'];
$mem_num = $r['mem_num'];
$mem_cat = $r['mem_category'];
echo "$name"."\t"."$email"."\t"."$phone"."\t"."$address"."\t"."$mem_num"."\t"."$mem_cat"."\n";
}
mysql_close($con);
?>
I believe you are confusing data-types here. A phone number for instance, is not a number. But it's called a number! Yeah I know, because it has a lot of numbers in it, but still, it isn't a number... Why?
A phone number is indeed constructed of a set of numerals - the symbols that represent a number - but that doesn't make it a number yet. Compare letters and words; a word is constructed of a set of letters, but not every set of letters is a word. For example: dfslkwpdjkcnj is not a word, not in a language I know of at least... And if it would be a number, how would you add-up two phone numbers? Or how would you divide a phone number by another one? Would that be something like [grandma's phonenumber] / [mom's phonenumber] = [my phonenumber]?
So, to store a phone number in a database, a varchar would be a more suitable column type. For example international phone numbers start with either a + sign, or double zero (00). Both of them can not be stored in a numeral field type. The + isn't a numeral sign, or is used to designate a positive number, and will be cut off. Leading zero's in a number have no function at all, and will be cut off as well...
So bottom line; in your database, use a varchar to store a phone number, and use conversion functions to format a phone number to your liking. There are almost certainly a dozen of algorithms to be found to format a phone number to some kind of a standardized format.
Then back to your excel: your aren't creating an excel file, but a csv file, and you're giving it an excel mime-type. But that would be the same to give someone a cd and say it is a dvd. If you put the cd in a dvd player, it will almost certainly be able to play it, but it is mere luck then wisdom that it does.
Creating an excel file isn't as easy as setting the mime-type, as you can't expect the browser to know how to convert text to an excel file, as it does not know about excel's internals. So if you reaaally want to create an excel file, and set the data types of certain columns, use a library like phpExcel or any other available, if you don't want to create a library yourself that is.
have you tried expanding(stretching) phone column in your excel file? sometime if column is small and numbers are big, excel displays number like(1.23+09) this.
If stretching column does not work. you can convert numbers into string and then put them in excel file
sorry i can't add this in comment as i don't have privilege to comment yet.
If with your API you are able to format cells, that's what you would need to do. You are storing your phone number as a BigInt instead of as a String. I have always stored phone numbers as Strings.
Excel is interpreting your data correctly--as a number, not as text. If you wish to continue to store your phone number as a BigInt (which I don't recommend), you would need to convert it to a String before writing it out to Excel. Or, if your API permits, write it out to Excel as a number, but then apply cell formatting to bring it to the formatting you expect.

numbers issue after export mysql data to CSV

when i get data from database and export it as a csv file i have following issues :
the leading zero of the numbers dosnt show
big numbers shows like this -> 1E+12
how to force MS Excel to show all of my data as string by PHP
You can use double quotes contain the numbers, like this:
if(is_numeric($column)) $column = '"'.$number.'"';
This isn't a MySQL issue, it's an Excel thing.
This... might help: http://answers.microsoft.com/en-us/office/forum/office_2007-excel/disabling-scientific-notation/943b8103-8c50-451d-8037-c697422e2307
But this question is more MS Office related than programming.
(or as comments suggested, use a file format that carries display formatting info, such as .xls)
I format it as a string by concatenate it with spaces at its start and end.
CONCAT(" ", database_number, " ") AS "Number For Excel".
Kai's answer didn't quite work for me. I ended up CONCATing an equals sign (still with the double quotes on either end) to the front and got the desired result. Our users wanted to be able to copy and paste the number straight out of Excel into our UI.
CONCAT('="',too_long_number_field,'"')
You can use number_formate() function to convert ...
View link
Function : number_format()
Syntax : number_format ( float $number , int $decimals = 0 , string $dec_point = ‘.’ , string $thousands_sep = ‘,’ )
Example to convert 6.90743E+11 to number use below code
number_format(6.90743E+11,0,'','') // outputs 690743000000

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.

Commercial round with comma and point

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.

Categories