duancaiyi7567 2018-07-15 21:31
浏览 56

如何格式化为货币[重复]

Having a lot of problems, I am using SUM on a field in my table and it works but only with one decimal place, I need it to be in currency format, I have tried the below code and others but nothing

$query = "SELECT purchase concat('$', sum(purchase), 2) from dtable"; 

$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
    echo "Total ". $row['SUM(purchase)'];
    echo "<br />";
}
</div>
  • 写回答

2条回答 默认 最新

  • doujia4619 2018-07-15 21:47
    关注

    First off, please don't use the mysql* functions as they are deprecated. Move to the mysqli* functions. See the PHP Docs for more details.

    How about this:

    SELECT CONCAT('$', ROUND(SUM(`purchase`), 2)) AS `result` 
    FROM `dtable`
    

    CONCAT just concatenates fields together so, in your case, you would end up with $###2. You need a function (like ROUND) to format the number as you want. ROUND take the number of desired decimal places as the first argument. More on ROUND (and other MySQL math functions) here: https://dev.mysql.com/doc/refman/8.0/en/mathematical-functions.html#function_round

    You could also do this all in PHP using number_format.

    Change

    $query = "SELECT purchase concat('$', sum(purchase), 2) from dtable";
    ....     
    echo "Total ". $row['SUM(purchase)'];
    

    to

    $query = "SELECT SUM(`purchase`) AS `sumOfPurchase` FROM `dtable`"; 
    ....
    echo 'Total $' . number_format($row['sumOfPurchase'], 2);
    
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度