寻找number_format()替代函数:仅保留非零小数位
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

