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

Vue过滤器实现小数格式化:保留两位小数且自动隐藏.00

Solution for Vue Filter Custom Number Formatting

Let's tweak your Vue filter to meet all your specific formatting rules exactly. The core challenge here is balancing consistent rounding with respecting the original input's structure (like whether it was an integer or a decimal value).

Modified Filter Code

Vue.filter("currency", value => {
  // Convert input to string to check its original structure
  const strValue = String(value);
  // Parse the value and round it to 2 decimal places
  const numValue = parseFloat(strValue);
  const fixedTwoDecimals = numValue.toFixed(2);

  // Case 1: Original input is an integer (no decimal point) → show 2 decimals
  if (!strValue.includes('.')) {
    return fixedTwoDecimals;
  }

  // Case 2: Rounded value ends with .00 → remove the decimal portion
  if (fixedTwoDecimals.endsWith('.00')) {
    return fixedTwoDecimals.slice(0, -3);
  }

  // Case 3: All other scenarios → keep the two decimal places
  return fixedTwoDecimals;
});

How It Handles Your Test Cases

Let’s walk through each of your required scenarios to confirm it works:

  • Original value: 1.00 (number or string "1.00"):
    The string version includes a decimal point, and fixedTwoDecimals is "1.00" → returns "1"
  • Original value: 1 (number or string "1"):
    The string has no decimal point → returns "1.00"
  • Original value: 1.6 (number or string "1.6"):
    fixedTwoDecimals becomes "1.60", which doesn’t end with .00 → returns "1.60"
  • Original value: 1.60 (number or string "1.60"):
    fixedTwoDecimals is "1.60", which doesn’t end with .00 → returns "1.60"
  • Original value: 1.451 (number or string "1.451"):
    toFixed(2) rounds the value to "1.45" → returns "1.45"

Key Logic Breakdown

  1. Preserve Input Context: Converting the input to a string lets us check if it was originally entered as an integer (no decimal point) or a decimal number.
  2. Consistent Rounding: toFixed(2) ensures we always round to two decimal places, covering cases like 1.451 that need truncation/rounding.
  3. Smart Conditional Formatting: We only hide the .00 suffix if the original input had a decimal point (meaning it was intended to be a decimal value). For integer inputs, we explicitly show two decimals as required.

内容的提问来源于stack exchange,提问作者Code Solution

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 12:02:47