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

表示从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
    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.

    点赞 评论

相关推荐