You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL Server查询与PHP中限制浮点值保留2位小数的问题求助

两种解决方法:SQL层面或PHP层面处理

一、直接在SQL语句中处理

你可以在SQL里用ROUND()函数直接将结果保留2位小数,修改后的语句如下:

when ap.idproduct = 1 then ROUND(cast(tr.PreviousBalance as float)/100, 2) 
else ROUND(cast(tr.FinalBalance as float)/100, 2) end as balance_before,

如果需要截断小数(不是四舍五入),比如把25.87999直接转为25.87而非25.88,可结合FLOOR()实现:

when ap.idproduct = 1 then FLOOR(cast(tr.PreviousBalance as float)/100 * 100)/100 
else FLOOR(cast(tr.FinalBalance as float)/100 * 100)/100 end as balance_before,

二、在PHP中处理输出

如果不想修改SQL,拿到查询结果后用以下PHP函数格式化(新手友好):

  • number_format():常用的数值格式化函数,支持控制小数位数和分隔符:
    // 假设从数据库取出的数值存在$balance变量中
    $formatted_balance = number_format($balance, 2);
    echo $formatted_balance; // 输出四舍五入后的两位小数,如25.88
    // 若不需要千位分隔符,可补充参数:
    $formatted_balance = number_format($balance, 2, '.', '');
    
  • sprintf():按指定格式精准输出,适合严格控制显示样式:
    $formatted_balance = sprintf("%.2f", $balance);
    echo $formatted_balance; // 输出四舍五入后的两位小数,如25.88
    // 如需截断小数,先通过计算处理再格式化:
    $formatted_balance = sprintf("%.2f", floor($balance * 100) / 100);
    
  • round():先对数值进行四舍五入处理,再输出:
    $rounded_balance = round($balance, 2);
    echo $rounded_balance; // 输出25.88
    // 第三个参数可指定截断模式:
    $truncated_balance = round($balance, 2, PHP_ROUND_HALF_DOWN);
    

内容的提问来源于stack exchange,提问作者Mnasri M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 08:35:31