而不是:
$price = "356";
$shipping = "0";
$total_price = $shipping + $price;
Price: <?php echo number_format((float)$price, 2, '.', ''); ?>
Shipping: <?php echo number_format((float)$shipping, 2, '.', ''); ?>
Total: <?php echo number_format((float)$total_price, 2, '.', ''); ?>我想使用这样的对象:
$price = "356";
$shipping = "0";
$total_price = $shipping + $price;
$oformat = new number_format(2, '.', '');
Price: <?= $oformat->format( (float) $price ); ?>
Shipping: <?= $oformat->format( (float) $shipping ); ?>
Total: <?= $oformat->format( (float) $total_price ); ?>但是我得到了:
Fatal error: Class 'number_format' not found in line...
为什么以及如何正确地做这件事呢?
发布于 2015-02-10 23:11:47
您要使用的类称为NumberFormatter。下面是一个例子:
<?php
$price = 356.12;
$shipping = 12.24;
$total_price = $shipping + $price;
$oformat = new NumberFormatter('en_EN', NumberFormatter::DECIMAL);
?>
Price: <?= $oformat->format( $price ); ?>
<br/>
Shipping: <?= $oformat->format( $shipping ); ?>
<br/>
Total: <?= $oformat->format( $total_price); ?>如果您没有可用的NumberFormatter,您可以创建自己的类:
<?php
class MyNumberFormatter
{
public function format($valueToFormat)
{
return number_format( $valueToFormat , 2, '.', '');
}
}
$price = 356.12;
$shipping = 12.24;
$total_price = $shipping + $price;
$oformat = new MyNumberFormatter();
?>
Price: <?= $oformat->format( $price ); ?>
<br/>
Shipping: <?= $oformat->format( $shipping ); ?>
<br/>
Total: <?= $oformat->format( $total_price); ?>发布于 2015-02-10 23:38:52
按照下一步操作:
wamp
创建另一个文本文件并将其命名为"main.php".
<?php require_once( "format.php“);//导入类。$fmt = new format();//创建您的类的对象$price = 356;$shipping = 0;$total_price = $shipping + $price;?>价格:发货:总价:
http://localhost:8099/main.php
说明:在一个单独的文件中创建一个类("format.php"),然后创建一个类的实例以便调用它的方法("number_format")。在一个单独的文件中更好,因为您可以重用该代码。
https://stackoverflow.com/questions/28434941
复制相似问题