我有这个功能,我想格式化一个数字,例如,如果它的整数如79,则该函数将其返回为$ 79,000,000.00。 否则,如果是79.5,则此函数将其返回为$ 79,500,000.00。
该功能如下,并且工作正常,您可以在http://www.compileonline.com/execute_php_online.php上进行测试:
function format_bolsa($number)
{
if(is_int($number))
{
echo '<p style="color:#0B3B0B">I am an INT and the number/value before processing is: ',$number,'</p>';
$number='$'.$number.',000,000.00';
echo '<p style="color:#0B3B0B">I am an INT and now the formatted number is: ',$number,'</p>';
return $number;
}
else if(is_float($number))
{
echo '<p style="color:#0B3B0B">I am a FLOAT and the number/value before processing is: ',$number,'</p>';
$number_tmp=explode('.',$number);
$number='$'.$number_tmp[0].','.$number_tmp[1].'00,000.00';
echo '<p style="color:#0B3B0B">I am a FLOAT and now the formatted number is: ',$number,'</p>';
return $number;
}
echo '<p style="color:#610B0B">Nothing has been done. The number is: ',$bolsa,' but such a value will not be returned!</p>';
}
$number=79;
$number=format_bolsa($number);
echo $number;
然而,当我把它插入这样的类(成为一个方法)时:
public function format_bolsa($number)
{
if(is_int($number))
{
echo '<p style="color:#0B3B0B">I am an INT and the number/value before processing is: ',$number,'</p>';
$number='$'.$number.',000,000.00';
echo '<p style="color:#0B3B0B">I am an INT and now the formatted number is: ',$number,'</p>';
return $number;
}
else if(is_float($number))
{
echo '<p style="color:#0B3B0B">I am a FLOAT and the number/value before processing is: ',$number,'</p>';
$number_tmp=explode('.',$number);
$number='$'.$number_tmp[0].','.$number_tmp[1].'00,000.00';
echo '<p style="color:#0B3B0B">I am a FLOAT and now the formatted number is: ',$number,'</p>';
return $number;
}
echo '<p style="color:#610B0B">Nothing has been done. The number is: ',$number,' but such a value will not be returned!</p>';
}
now方法无法正常工作,我收到自定义消息
什么都没做。号码是:&#39;,$ number,&#39;但这样的价值会 不归还!
我这样称呼方法:
$number=self::format_bolsa($number);
我不知道为什么它不起作用。我已经插入了这样的其他功能,它们现在作为方法正常工作。
任何人都可以解释一下吗?
答案 0 :(得分:1)
为什么不简单地使用number_format?
echo number_format(79 * 1000000, 2);
echo number_format(79.5 * 1000000, 2);
Else ..有一个工作示例可以帮助您使用静态方法:
class Test
{
public static function format_bolsa($number)
{
if (is_int($number)) {
echo 'I\'m an int';
}
else if (is_float($number)) {
echo 'I\'m a float';
}
}
}
Test::format_bolsa(79);
Test::format_bolsa(79.5);
现在使用number_format:
class Test
{
public static function format_bolsa($number)
{
return number_format($number * 1000000, 2)
}
}
同时阅读静态方法不好的原因:static considered harmful
答案 1 :(得分:1)
你应该打电话:
$number=$this->format_bolsa($number);