tctc91
tctc91

Reputation: 1363

Require 2 decimal places after the point in PHP?

I'm working with currencies so for example -

5 is OK as it is interpreted as 5.00. But 5.005 is not as it has too many digits after the point.

How can I restrict the amount of digits and show an error if there's too many?

Thanks

Upvotes: 1

Views: 2411

Answers (5)

paxdiablo
paxdiablo

Reputation: 882326

The following code will capture a number of things from a user-entered string:

  • too many decimal points, such as 1.2.3.
  • more than two digits in second section (if there), such as 1.234.
  • any non-numerics in first or second section, such as 123.4a or 1a3.45.
  • both first and second section empty, such as ..

$x = '12.34';
$parts = explode('.', $x);
$nm0a = preg_match ('/^[0-9]*$/', $parts[0]);
$nm0b = preg_match ('/^[0-9]+$/', $parts[0]);
$nm1a = preg_match ('/^[0-9]*$/', $parts[1]);
$nm1b = preg_match ('/^[0-9]+$/', $parts[1]);

if (count ($parts) > 2)           { die ("Too many decimal points"); }
if ($nm0a == 0)                   { die ("Non-numeric first part"); }
if ($nm1a == 0)                   { die ("Non-numeric second part"); }
if (($nm0b == 0) && ($nm1b == 0)) { die ("Both parts empty"); }
if (strlen ($parts[1]) > 2)       { die ("Too many digits after decimal point"); }

die ("Okay");  # Only here to provide output.

Upvotes: 0

Umbrella
Umbrella

Reputation: 4788

number_format will correct it for you, but if you want to error when too much precision is provided, you will need to test it.

$x = 12.345;
if ($x != number_format($x, 2)) {
    // error!
}

Upvotes: 2

Nick
Nick

Reputation: 6346

I usually use sprintf

$formatted = sprintf("%01.2f", $price);

But there are many other functions / solutions you could use.

Upvotes: 0

Wes Crow
Wes Crow

Reputation: 2967

You can format the number like this:

 $num = 50695.3043;
 $num = number_format( $num, 2, '.' );
 echo $num;

This will result in:

 50695.30

Note that this rounds. So 1.566 would round to 1.57.

Upvotes: 0

Marc B
Marc B

Reputation: 360802

$x = '5.005'; // declare as string to avoid floating point errors
$parts = explode('.', $x);
if (strlen($parts[1]) > 2) {
   die("Too many digits");
}

Upvotes: 2

Related Questions