decimal delimiter in mysql for cakephp app - php

I have a CakePHP 1.3 website with a MySQL database. The problem is that i have some prices, double values, that are stored using a dot as a decimal delimiter, however my application front-end should display them using commas.
Is there a way to set this in the DB directly, or simply a better way to achieve this than str_replace EVERYWHERE? that would be such a hassle, and it just seems like bad practice to me.
Thank you in advance!

The decimal in the database is correct- it's a decimal being used as a decimal. To display it, you should use number_format for presentation.

You could technically just do n str_replace in the model's afterFind handler and forget about it.

$decimalNumberFromDb= 1234.56;
//
// French notation
//
$frenchNotation = number_format($decimalNumberFromDb, 2, ',', ' '); // Output: 1 234,56
//
// English Notation
//
$englishNotation = number_format($decimalNumberFromDb, 2, '.', ''); // Output: 1234.56

The dot in your database is not a delimiter but the way decimals are stored.
You could do a select query like this
select *, REPLACE(CAST(price AS CHAR), '.', ',') as price_formatted from products;
Or with display it with PHP in other formats with number_format
$price = 1300222.99;
echo "Original: ".$price.PHP_EOL;
echo "english/us: ".number_format($price,2).PHP_EOL;
echo "Dutch/german: ".number_format($price, 2, ',', '.').PHP_EOL;
echo "French: ".number_format($price, 2, ',', ' ').PHP_EOL;
echo "Swiss: ".number_format($price, 2, ',', '\'').PHP_EOL;
example at http://codepad.org/WXjc7d2D

you can use behaviors which do that for you:
https://github.com/dereuromark/tools/blob/2.0/Model/Behavior/DecimalInputBehavior.php

Related

How can I get number from a special string ? PHP

For example, 3 string are the following :
##7##
##563##
##120058##
How can I get those number like this :
echo first number is 7
echo second number is 563
echo third number is 120058
Thank you very much!
$numberAsString = trim($string, '##')
Is probably the easiest and fastest in this case. The output is still a string in this case, but in most cases that doesn't really matter. If it does in your case, you can use (int), (float) or the like to get it to the correct type.
Of course, regex would also be possible, e.g.:
$didMatch = preg_match('/#+([^#]+)#+/', $string, $matches);
Another possibility still is first extract the remaining part after the initial 2 # and then cast to a number, which seems to be always int in this case:
$number = (int)substr($string, 2);
Still another possibility would be to go by the count of the characters and just use substr like:
$numberAsString = substr($string, 2, -2);
Or you could be creative and use something like explode + implode + array functions:
$numberAsString = array_slice(explode('#', implode('', array_slice(explode('#', $string), 2))), 0, -2);
Of course, this last one is purely to show that it can be done in various ways, as it's very inefficient and impractical, but there are surely dozens of other ways.
In case you use this in a tight loop or somewhere where performance really matters, I would benchmark different possibilities - on a guess, I'd say that either the trim or the pure substring solution would be the fastest.
$str = "##563##";
preg_match("|\d+|", $str, $res);
print_r($res);
Just call the filter_var() function it will return the number only.
Whatever the input is, it will only filter the number for you!
filter_var("##120058##", FILTER_SANITIZE_NUMBER_INT) // return 120058
filter_var("*##20kkk", FILTER_SANITIZE_NUMBER_INT) // return 20

How can I stop PHP from changing all my decimal separators?

My (MySQL) tables have columns with currency values set as Decimal(10,2) with decimals separated by commas. However whenever i query them, php turns all my commas into periods and invalidates my results. Can I stop it doing that? It affects both my SELECT and my INSERT/UPDATE.
When I select, for example, 123,00 php turns it into 12300.00; same for inserting a number: i insert 123,00 but the value in the table becomes 12300,00 again. Is there a way to make comma the default decimal separator?
have you looked in to
http://php.net/manual/en/function.money-format.php
$number = 1234.56;
// let's print the international format for the en_US locale
setlocale(LC_MONETARY, 'en_US');
echo money_format('%i', $number) . "\n";
For the PHP part this might me helpful
<?php
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
This should give you a clue on how to get the right output from your PHP code.
Don't care on how the database stores your numbers, neither on how PHP does it internally.
Use the number_format to get your desired output.
See also PHP: number-format for more on that.

php preg_match_all results from (numerical) STRING to DECIMAL - type

I have script that identifies with preg_match_all some numbers from a given file and in a given format '#(\d\,\d\d\d\d)#' (decimal, with 4 decimals). With them, later, I need to do some math operations to find out the sum, average etc.
With print_r I can see all matches from the array and it is ok (4,3456, 4,9098, etc.). I verify the type of variables and gettype() returned string
Unfortunately I cannot do math operations with them because when I use the variables in a math expression the result is always rounded regardless of what came afer the comma.
For example:
4,3456 + 4,9098 + 4,3456 = 12, or 12,0000 -- if I use number_format.
I used . instead of , in the numbers, I formatted the results with number_format, but have had no success. It seems I am missing something.
Thanks for help!
The error happens even before the number_format call -- PHP considers . as the decimal separator, not ,. you need to str_replace all your array elements:
$values_array = str_replace(",", ".", $values_array)
PHP uses the . character as decimal separator, so you have to replace the , by a . in your matched numbers before converting them to numbers:
$number = floatval(strtr("1,234", ",", "."));
// 1.234
Example:
<?php
$numbers = array("1,234", "5,67");
$numbers = str_replace(",", ".", $numbers);
echo number_format($numbers[0] + $numbers[1], 4, ',', ' ');
Try it here: http://codepad.org/LeeTiKPF

Decimal number with comma instead of point (php and sql)

I'm doing a little application of adding prices and decimals. Points are normal to use with decimals, but how can I write decimal number with comma as input (543,35 instead of 543.35) and then maybe change it with point to the database (mysql)? Then print it back form the database with the comma. Reason is that comma (,) is more used in Finland than point (.) when write decimal numbers.
Thank you very much!
Samuel
$input = '5,50';
$output = str_replace(',', '.', $input);
var_dump($output); // string(4) "5.50"
$number = (float)$output;
var_dump($number); // float(5.5)
you need not do anything in the sql end. you want to format the decimal value in php (this assumes php4/php5): Set the third parameter $dec_point to ','
// string number_format ( float $number , int $decimals , string $dec_point , string $thousands_sep )
<?php
$number = 1234.56;
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
source:
http://php.net/manual/en/function.number-format.php
Cheers!
the PHP number_format function is what you need :
number_format(5.50, 2, ',');
...should do the trick.
As it's been said, it's best to save the value as a float and then format for display. As an alternative to the previously suggested number_format(), you could try money_format() http://us.php.net/manual/en/function.money-format.php It doesn't work in a windows environment though if that is important to you.
No, using comma as a decimal separator for arithmetic operations is not supported. Filter your input and replace the comma with a period, then format your output as you wish.

How to check how many characters in variable, and add space between characters in that var?

I have a 'price' variable that contains some integer number from a MySQL database.
I want to check how many numbers the 'price' variable contains, and add a space in the variable depending on how many numbers. See below:
Example:
If 'price' is 150000 I would like the output to be 150 000 (notice the space).
OR, if it is 19000 I would like it to output 19 000...
How would you do this the easiest way?
The easiest way is to use number_format():
$str = number_format($number, 0, '.', ' ');
Use the number_format function to format a number:
number_format($number, 0, '.', ' ')
If what you are trying to do is format the number with grouped thousands and a space as the thousand separator, use this.
number_format($number, 2, '.', ' ');

Categories