在PHP中,需要小数点后2位


Require 2 decimal places after the point in PHP?

我正在处理货币,例如-

5是可以的,因为它被解释为5.00。但5.005并不是因为它在点后有太多数字。

如果数字太多,我如何限制数字的数量并显示错误

感谢

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

number_format将为您更正它,但如果您想在提供太多精度时出错,则需要对其进行测试。

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

您可以这样格式化数字:

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

这将导致:

 50695.30

请注意,这是圆形的。因此1.566将四舍五入到1.57。

我通常使用sprintf

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

但是,您还可以使用许多其他功能/解决方案。

以下代码将从用户输入的字符串中捕获许多内容:

  • 小数点过多,如1.2.3
  • 第二部分中的两个以上的数字(如果有的话),例如1.234
  • 第一或第二部分中的任何非数字,例如123.4a1a3.45
  • 第一和第二部分都是空的,例如.

$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.