Laravel 6.20电商网站商品页折扣百分比保留两位小数实现求助
Hey there! I see you're working on your Laravel 6.20 e-commerce site and want to display discount percentages with two decimal places instead of whole numbers. Let's get that sorted out quickly.
The Issue with Your Current Code
Right now, you're using the round() function which truncates the result to an integer. To show two decimal places, we need to use a formatting function that preserves those decimals.
Modified Code with Two Decimal Places
Here's how you can update your Blade template code. We'll use PHP's number_format() function, which lets us specify exactly how many decimal places to keep:
<ul class="product_marks"> @if($row->discount_price != NULL) <li class="product_mark product_discount"> -{{ number_format(($row->discount_price / $row->selling_price) * 100, 2) }}% </li> @endif <li class="product_mark product_new">NEW</li> </ul>
How It Works
number_format()takes two key arguments here:- The calculated discount percentage (
($row->discount_price / $row->selling_price) * 100) 2to specify we want exactly two decimal places
- The calculated discount percentage (
This will output values like -15.75% or -20.00% instead of just -16% or -20%.
Alternative: Using sprintf()
If you prefer, you can also use sprintf() for formatting, which gives you similar control:
<li class="product_mark product_discount"> -{{ sprintf('%.2f', ($row->discount_price / $row->selling_price) * 100) }}% </li>
Quick Check: Discount Calculation Logic
Just a heads up: Double-check that your variable names align with your intended calculation. For example, if discount_price is the discounted (final) price (not the discount amount), your current formula will show the percentage of the original price that the customer pays (e.g., 80% for a 20% discount). If that's not what you want, adjust the formula to:
(($row->selling_price - $row->discount_price) / $row->selling_price) * 100
This would calculate the actual percentage off the original price.
内容的提问来源于stack exchange,提问作者Masudalimran

