Solved

php parse percentage or currency string to number

Posted on 2014-11-20
3
279 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 83

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 50 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 110

Accepted Solution

by:
Ray Paseur earned 450 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
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…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

615 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