Solved

PHP Validate a string is a valid currency decimal

Posted on 2010-09-10
2
624 Views
Last Modified: 2012-05-10
Hi,

Given some user input I want to validate a string is an integer and convert this to a (foat,decimal) number to 2 d.p.

Input examples

7 ==> 7.00
70 ==> 70.00
70.3 ==> 70.30
70.35 ==> 70.35
40.995 ==> 41.00
40.994 ==> 40.99
70.54p ==> not valid
$70.00 ==> Not valid ($)
70GBP ==> Not valid (GBP)

Many thanks,




0
Comment
Question by:bigMlittleC
2 Comments
 
LVL 6

Assisted Solution

by:Mike D
Mike D earned 200 total points
ID: 33644566
Hi bigMlittleC,

I realize you're asking for PHP but since I found this under JS and my code should work similar in PHP here it is (I did this for a german customer hence the ',' [comma] and you would have to include a rounding function for 3 digits behind the decimal point scenario):

if(tot_price.indexOf(".") != -1) {
      fancy_tot_price = tot_price.substring(0, tot_price.indexOf(".")) + "," + tot_price.substring(tot_price.indexOf(".")+1, tot_price.length) + '0'      
}
else
      fancy_tot_price = tot_price + ',00'


Hope this helps!

greets
JD
0
 
LVL 12

Accepted Solution

by:
Mohamed Abowarda earned 300 total points
ID: 33644598
First, you have to use is_numeric function to insure that the input is a number, then you can use strpos function to check if the string contains dot "." so you can know if it's decimal or integer.

is_numeric:
http://php.net/manual/en/function.is-numeric.php

strrpos:
http://php.net/manual/en/function.strrpos.php
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

792 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