Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

php parse percentage or currency string to number

Posted on 2014-11-20
3
Medium Priority
?
372 Views
Last Modified: 2014-11-20
Experts,

I've searched the manuals and tried their examples.  None seem to work.

Please provide a snippet to show how to store a post of 50% or $250.00 to  MySql as numbers.

Capt
0
Comment
Question by:Glen Gibb
3 Comments
 
LVL 84

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 200 total points
ID: 40454763
Get rid of the '%' and the '$' because those are not part of numbers as far as MySQL (and most programming languages) are concerned.  With those characters, it can only be text, not numbers.  This bit of code may do what you need.

$punctuation = array("%", "$");
$onlynumbers = str_replace($punctuation, "", $numberstring);

Open in new window

0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 1800 total points
ID: 40454790
I use a regular expression to remove all of the non-numeric data, leaving only the +, -, ., and digits.  This is untested code, but I think I'm remembering it correctly...

$num = preg_replace('#[^0-9\+\-\.]#', NULL, $string);

Open in new window


Then I store the resulting values into MySQL columns defined as DECIMAL, using the appropriate bounds.  For dollars and cents you might choose DECIMAL(10,2).
0
 

Author Closing Comment

by:Glen Gibb
ID: 40455367
Thanks, Experts.  Easy peasy.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo‚Ķ
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses

971 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question