而不是:
$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...
为什么以及如何正确地做到这一点?
答案 0 :(得分:0)
您要使用的课程称为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); ?>
答案 1 :(得分:0)
按照以下步骤操作:
<?php class format { public function number_format ( $num , $dec, $sep ) { // ADD YOUR CODE HERE. return $num; } } ?>
< ? php require_once( "format.php" ); // IMPORT CLASS. $fmt = new format(); // CREATE OBJECT OF YOUR CLASS. $price = 356; $shipping = 0; $total_price = $shipping + $price; ?> Price : <?php echo $fmt->number_format( $price,2,"." ); ?> <br/> Shipping : <?php echo $fmt->number_format( $shipping,2,"." ); ?> <br/> Total price : <?php echo $fmt->number_format( $total_price,2,"." ); ?>
启动wamp服务器(屏幕右下方的绿色图标)。
打开任何浏览器并在地址栏中输入下一行:
说明:在一个单独的文件中创建一个类(&#34; format.php&#34;),然后创建一个类的实例以调用它的方法(&#34; number_format&#34;) 。在单独的文件中更好,因为您可以重复使用该代码。