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

寻找number_format()替代函数:仅保留非零小数位

Solution for Conditional Decimal Display in PHP

Great question! PHP doesn’t have a built-in function that directly handles "only show decimals when the fractional part is non-zero" out of the box, but there are a couple of straightforward ways to achieve exactly what you need.

Method 1: Type Conversion Check

This approach leverages PHP’s type handling to distinguish between whole numbers and values with non-zero fractional parts:

function formatConditionalDecimal($number) {
    // Convert to float to strip trailing zero decimals
    $floatVal = (float)$number;
    // Return as integer if it's a whole number, else return the float
    return $floatVal === (int)$floatVal ? (int)$floatVal : $floatVal;
}

// Test with your values
$testNumbers = [175.0000, 185.0000, 195.0000, 205.0000, 13.0000, 15.0000, 10.5000, 7.5000];
foreach ($testNumbers as $num) {
    echo formatConditionalDecimal($num) . "\n";
}

Output:

175
185
195
205
13
15
10.5
7.5

This works perfectly for your dataset: whole numbers with .0000 get stripped down to integers, while values like 10.5000 retain their .5 fractional part.

Method 2: String Replacement (Targeted for Your Case)

If you want to stick close to number_format() and just clean up unnecessary .0 suffixes, use a regex replacement:

function formatConditionalDecimal($number) {
    // Format to 1 decimal place as you initially tried
    $formatted = number_format($number, 1);
    // Remove trailing .0 from whole numbers
    return preg_replace('/\.0$/', '', $formatted);
}

This method first ensures your non-whole values show .5 (via number_format), then strips the .0 from whole numbers—ideal for your specific set of inputs.

Both approaches are lightweight and will handle your use case flawlessly. Pick whichever fits best with your codebase!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:28:37