当表示从 MySQL 数据库中获取的 "money" 属性时,在 PHP 中使用的正确格式是什么?

What is the correct format to use in PHP when denoting "money" attribute fetched from MySQL database?

我正在使用 "number_format" 函数来表示 PHP/MySQL 中的 money" 属性。

属性本身存储在我的数据库中。

  Select account_balance from my_table where login = 'xxxxxx';
  $correct_account_balance = number_format($account_balance,
  ['my_balance'],2);  }

换句话说:表示法“2”会在小数点后多加两位,如下:10.00(对于示例)

此代码工作正常......除了一个小问题:如果小数点后的金额末尾为零,则不显示!

例如:如果金额是 10 美元 35 美分,它会正确显示:10.35

但是,如果金额为 10 美元和 30 美分,则显示为:10.3(而不是:10.30

原因是:在我使用 "number_format" 函数转换后,我的程序还在 account_balance 上执行算术运算。

例如:

     $correct_account_balance -= 0.25   (this will subtract 0.25 each time the program is executed)

这就是为什么任何时候在实际金额末尾有一个“”(例如:10.30),它显示为:10.3

有没有办法解决这个问题? Google好像不知道;

The reason is : my program also performs arithmetical operations on the account_balance AFTER I have converted it using the "number_format" function.

操作完成后需要重新运行number_format

在准备好显示之前,您根本不应该 运行 它,或者,它添加到较大数字的逗号会 极大地 打乱您的计算。例如,以下内容:

<?php

$number = 100000.30;
$number = number_format($number, 2);
$number -= 0.25;
echo number_format($number, 2);

输出结果:

99.75

这意味着您刚刚因类型转换错误从客户那里偷走了 99,900.55 美元。