Prestashop中如何让价格显示带末尾0的两位小数?
Hey there! I see you're working with PrestaShop's Tools::ps_round to fetch product prices without discounts, but it's returning 59.4 instead of the clean 59.40 you need for display. Let's fix this with a couple of simple, reliable approaches:
Option 1: Use number_format()
Wrap the rounded price result with number_format() to enforce exactly two decimal places—even when the second digit is a zero:
$rawPrice = Tools::ps_round((string)$prod->getPriceWithoutReduct(), 2); $formattedPrice = number_format((float)$rawPrice, 2, '.', ''); // Output will be "59.40" instead of "59.4"
(float)$rawPriceconverts the rounded string back to a numeric value so we can format it- The
2tells PHP we want exactly two decimal places '.'sets the decimal separator, and the empty string''removes any unwanted thousands separators (adjust this if your store uses them)
Option 2: Use sprintf()
Another straightforward method is using sprintf() for precise string formatting:
$rawPrice = Tools::ps_round((string)$prod->getPriceWithoutReduct(), 2); $formattedPrice = sprintf("%.2f", (float)$rawPrice); // This will also output "59.40"
%.2fis a format specifier that forces PHP to render the number as a float with two fixed decimal places
Quick explanation of the root issue
The Tools::ps_round function trims trailing zeros after the decimal point because numerically, 59.4 and 59.40 are identical. But for pricing displays, we need that trailing zero to keep consistency—hence why wrapping the result with a formatting function like number_format or sprintf is necessary.
内容的提问来源于stack exchange,提问作者Francisco L

