Solved

PHP Validate a string is a valid currency decimal

Posted on 2010-09-10
2
586 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:johndoeherty
johndoeherty 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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

743 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

11 Experts available now in Live!

Get 1:1 Help Now