doubang4881 2015-04-27 17:46
浏览 80
已采纳

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

I'm using the "number_format" function to denote money" attribute in PHP/MySQL.

The attribute itself is stored in my database.

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

In other words : the denotation "2" will add two extra numbers after the decimal point, as follows : 10.00 (for example)

This code works fine............except for one small problem : if the amount after the decimal point has a zero at the end, it does not display!

For example : if the amount is, say, 10 dollars and 35 cents, it displays correctly : 10.35

However, if the amount is 10 dollars, and 30 cents, it displays as : 10.3 (instead of : 10.30 )

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

For example :

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

This is why, anytime there is a "zero" at the end of the actual amount (like : 10.30), it displays as : 10.3

Is there anyway to get around this? Google doesn't seem to know;

  • 写回答

1条回答 默认 最新

  • dongwopu8210 2015-04-27 17:50
    关注

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

    You'll need to re-run number_format after doing the operations on it.

    You really shouldn't run it at all until it's ready for display, either, the commas it adds to larger numbers will hugely mess up your calculations. As an example, the following:

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

    results in the output:

    99.75
    

    Which means you've just stolen $99,900.55 from your customers with a type conversion error.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 数学的三元一次方程求解
  • ¥20 iqoo11 如何下载安装工程模式
  • ¥15 本题的答案是不是有问题
  • ¥15 关于#r语言#的问题:(svydesign)为什么在一个大的数据集中抽取了一个小数据集
  • ¥15 C++使用Gunplot
  • ¥15 这个电路是如何实现路灯控制器的,原理是什么,怎么求解灯亮起后熄灭的时间如图?
  • ¥15 matlab数字图像处理频率域滤波
  • ¥15 在abaqus做了二维正交切削模型,给刀具添加了超声振动条件后输出切削力为什么比普通切削增大这么多
  • ¥15 ELGamal和paillier计算效率谁快?
  • ¥15 蓝桥杯单片机第十三届第一场,整点继电器吸合,5s后断开出现了问题