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

Liquid价格格式化需求:小数为0显示整数,否则保留原价格(round:1无效)

Liquid价格格式化:小数为0时显示整数,否则保留原格式

你遇到的问题是round:1过滤器无法满足需求——它只会四舍五入保留一位小数,没法自动判断小数部分是否为0来切换显示格式。下面是两种可行的实现方式:

方式一:条件判断语句

先把价格转为浮点型,再对比它和自身的整数部分是否相等,以此决定显示格式:

{% assign price = 19.99 | divided_by: 1.0 %} <!-- 确保是浮点数值 -->
{% if price == price | floor %}
  {{ price | floor }} <!-- 小数部分为0时显示整数 -->
{% else %}
  {{ price }} <!-- 否则保留原格式 -->
{% endif %}

测试示例:

  • 当price为20.0时,输出20
  • 当price为19.99时,输出19.99
  • 当price为15.5时,输出15.5

方式二:三元运算符(简洁版)

如果你的Liquid环境支持三元表达式(比如Shopify Liquid),可以用更紧凑的写法:

{% assign price = product.price | divided_by: 1.0 %}
{{ price == price | floor ? price | floor : price }}

补充说明

  • divided_by: 1.0的作用是将整数类型的价格转为浮点型,避免整数和浮点数对比时出现判断错误
  • 如果你的价格是字符串格式(比如从API获取的"20.00"),可以先用plus: 0转为数值:
    {% assign price_str = "20.00" %}
    {% assign price_num = price_str | plus: 0 %}
    {% if price_num == price_num | floor %}
      {{ price_num | floor }}
    {% else %}
      {{ price_str }}
    {% endif %}
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 17:40:18