How to change decimal separator cleanly in outputs in mysql - php combo
-
09-04-2021 - |
Question
I was trying to export database query to CSV and the need arised to use different decimal comma. It seems impossible to change the decimal comma in MySQL, so I tried in PHP:
setlocale(LC_NUMERIC, "cs_CZ");
But it seems that all the database functions like mysql_fetch_row
and mysql_fetch_assoc
are retrieving data of type string
instead of double
:
$res = mysql_query("select 50/3");
$row = mysql_fetch_row($res);
var_dump($row); // $row[0] is of type "string"
So in general PHP already doesn't have data of type double
, but only strings!
So is there some general, clean way to specify output of the decimal point?
I ended up converting the strings using str_replace('.', ',', $row[0])
but this is ugly for two reasons:
- you have to know which field is of type
double
- it's a dirty string job.
Solution
I don't know which database client/driver you're using but there is something like mysql_field_type
Docs which gives you the type based on it's offset, like 0.
This should do the job to find out if a certain column needs re-formatting or not.
To reformat, there is number_format
Docs.
With these you can do the conversion automatically.
Edit: Regarding your comments:
If you want to get PHP datatypes mapped, consider using the MySQL Native DriverDocs. Use it together with PDO:
Advantages of using mysqlnd for PDO
mysqlnd returns native data types when using Server-side Prepared Statements, for example an INT column is returned as an integer variable not as a string. That means fewer data conversions internally. Source
So depending of what you try to achieve, use the right tool.
See as well the multiple options you have when fetching data from a PDO StatementDocs.
OTHER TIPS
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
Try
number_format($row[0], 2, ",", ".");
That should change the format of the number. (german format)