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

Laravel 6.20电商网站商品页折扣百分比保留两位小数实现求助

Fixing Two-Decimal Discount Percentage in Laravel 6.20 Product Page

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)
    • 2 to specify we want exactly two decimal places

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:58:14