PHP 格式字符串到由两个小数点分隔的数字


PHP format string to numbers seperated by two decimal points

用户可以按以下格式输入值:

  • 1.00
  • 1
  • 1,00

现在我需要返回使用两个小数点 (,) 格式化的此值。当我使用:

number_format($request->金额,2,",",")

并使用"1,00"作为输入,我收到此错误:

Notice: A non well formed numeric value encountered

解决此问题并仍然能够处理所有三种类型的输入的最佳方法是什么?

下面是一个简短的示例:

input of user:|output:
1.00           1,00
1              1,00 
1,51           1,51

以下方法应该有效:

$request->amount = str_replace(",", ".", $request->amount);
number_format($request->amount, 2, ',','');

试试这个:

number_format((int)$request->amount, 2, ',','');