Jam*_*son 3 javascript php decimal
我有一个基本的index.php页面,其中包含一些我想在几个地方打印的变量 - 这里是变量:
<?php
$firstprice = 1.50;
$secondprice = 3.50;
$thirdprice = 20;
?>
Run Code Online (Sandbox Code Playgroud)
我的挑战是,在文档的后面,当我打印时,我得到的价格没有第二个'0'的价格 - 这就是发生的事情:
<?php print "$firstprice";?> // returns 1.5 - not 1.50!
Run Code Online (Sandbox Code Playgroud)
所以 - 我知道如何用JS做到这一点,但是如何在PHP 5+中完成?基本上我想打印第二个'0',如果已经有一个小数,所以如果变量等于'3',它保持为'3',但如果它等于'3.5',它转换为显示'3.50'用第二个'0'等
这是一个JS示例 - 什么是PHP等价物?
JS:
.toFixed(2).replace(/[.,]00$/, ""))
Run Code Online (Sandbox Code Playgroud)
非常感谢!!
Jon*_*Jon 10
这很简单,它还可以让你调整格式:
$var = sprintf($var == intval($var) ? "%d" : "%.2f", $var);
Run Code Online (Sandbox Code Playgroud)
%d如果它没有小数,它会将变量格式化为整数(),如果它有小数部分,则将其格式化为两位小数(%.2f).
更新:正如Archimedix所指出的,3.00如果输入值在范围内,这将导致显示(2.995, 3.005).这是一个改进的检查,修复了这个问题:
$var = sprintf(round($var, 2) == intval($var) ? "%d" : "%.2f", $var);
Run Code Online (Sandbox Code Playgroud)
<?php
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
// 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
// 1 234,56
$number = 1234.5678;
// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
?>
Run Code Online (Sandbox Code Playgroud)
更多信息,请访问 http://php.net/manual/en/function.number-format.php