Home » , , » Php function to validate two decimal places of a number

Php function to validate two decimal places of a number

Written By Unknown on Selasa, 04 Mei 2010 | 01.11


If you are looking for the validation of a number which contains only two decimal places. Means you want to accept the values like 0.21 or 1.34 or 12.55 or 445.66 as a input and throw an error when somebody enters the number like 0.2 or 4.678 from a text box. Here is a simple function for you in PHP which validates the number weather it contains exactly two decimal places or not.

Function to validate two decimal places of a number in PHP


function validateTwoDecimals($number)
{
   if(ereg('^[0-9]+\.[0-9]{2}$', $number))
return true;
   else
return false;
}

Well let me explain the fairly simple regular expression inside the ereg() function of PHP.

^[0-9]+\.[0-9]{2}$

The hat(^) represents the start of the string and the [0-9]+ tells that there will be one or more digits at the starting of the the string. “‘\.” represents that there should be a period(.) after that and [0-9]{2} tells that after there should be exactly two digits after period and the dollar sign($) represents the end of the string.


Share this article :

Posting Komentar

 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. Kumpulan Kata Broadcast Blackberry - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger