Solved

php parse percentage or currency string to number

Posted on 2014-11-20
3
244 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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

756 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