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, andfixedTwoDecimalsis"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"):fixedTwoDecimalsbecomes"1.60", which doesn’t end with.00→ returns"1.60" - Original value: 1.60 (number or string
"1.60"):fixedTwoDecimalsis"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
- 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.
- Consistent Rounding:
toFixed(2)ensures we always round to two decimal places, covering cases like1.451that need truncation/rounding. - Smart Conditional Formatting: We only hide the
.00suffix 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
相关产品推荐
相关产品推荐

