Solved

PHP Validate a string is a valid currency decimal

Posted on 2010-09-10
2
602 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

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.
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.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

948 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now