Re: Removing commas from number

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Paul -

You make a good point.  What is your suggestion for the following sequence:

$number = $row->AMOUNT; // Get the double from MySQL

To display the number in the HTML edit field, I do

$display_number = number_format($number, 2, '.', '');

The user may enter a character that will not be accepted by MySQL, so I do

$mysql_number = preg_replace('/[^0-9^\.]/', '', $display_number);

Thank you for your suggestions....

Todd

Paul Novitski wrote:
At 5/6/2007 08:33 AM, Todd Cary wrote:
Thanks to the suggestions, I use number_format($my_number, 2) to format the number in an edit field. Now I need to reenter it into MySQL. How should I use preg_replace to remove the commas?

This removes the commas *and* the decimal point:

preg_replace('/\D/', '', $str)


This strikes me as such an odd thing to do. If the MySQL table field is defined as float, I don't see the need to remove the decimal point.

If you do need to store the digits without the punctuation, you could also multiply by 100 and store it as an integer: intval($my_number * 100) which seems more efficient than to format as a string and then reformat without the punctuation.

If I have two uses for a number -- say, formatted with commas and other dressing for display and formatted more severely for SQL -- I'd retain the number in a variable as its pure value and convert it for each use, rather than converting it for one use and then converting that for the next use. The software's more robust because a glitch in a formatting operation isn't going to affect the final result. Also, in many arithmetic circumstances where division is involved, the true value of the results are accurate to more than two decimal places. While these might be rounded to the nearest cent for display purposes, you'll want to add the true values to get the true total. One common example is a column of percentages that should add to 100%.

Regards,

Paul
__________________________

Paul Novitski
Juniper Webcraft Ltd.
http://juniperwebcraft.com

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux