基于Intl.NumberFormat实现格式化货币值的小数条件移除
Got it, let's tackle this problem step by step. You need to adjust your existing formatMoneyValue function to follow those three specific decimal rules, while keeping the core GBP currency formatting from Intl.NumberFormat. Here's how to do it:
Step-by-Step Explanation
First, let's recap your rules to make sure we align:
- Rule 1: Values < 100 → keep decimals (always show 2 decimal places, standard for currency)
- Rule 2: Values > 99.9 with
.00decimals → remove the decimal part entirely - Rule 3: Values > 99.9 with non-zero decimals → keep the decimals
The key here is to dynamically adjust the decimal digit options passed to Intl.NumberFormat based on the input value, instead of using a fixed configuration.
Modified Function Code
function formatMoneyValue(value) { let fractionConfig; if (value < 100) { // Rule 1: Values under 100 always show 2 decimal places fractionConfig = { minimumFractionDigits: 2, maximumFractionDigits: 2 }; } else { // Check if there's any non-zero decimal part const hasNonZeroDecimals = value % 1 !== 0; if (hasNonZeroDecimals) { // Rule 3: Values over 99.9 with decimals keep them fractionConfig = { minimumFractionDigits: 2, maximumFractionDigits: 2 }; } else { // Rule 2: Values over 99.9 with .00 decimals hide them fractionConfig = { minimumFractionDigits: 0, maximumFractionDigits: 0 }; } } // Combine currency settings with dynamic decimal config and format return new Intl.NumberFormat('en-GB', { style: 'currency', currency: 'GBP', ...fractionConfig }).format(value); }
Test Cases to Verify
Let's check some examples to confirm it works as expected:
formatMoneyValue(45.75)→£45.75(Rule 1)formatMoneyValue(99.90)→£99.90(Rule 1, since it's under 100)formatMoneyValue(100.00)→£100(Rule 2)formatMoneyValue(125.50)→£125.50(Rule 3)formatMoneyValue(99.91)→£99.91(Rule 3, since it's over 99.9 with non-zero decimals)
Note on Floating Point Precision
Keep in mind that floating point numbers can have tiny precision errors (e.g., 100.0 might be stored as 99.99999999999999 in some cases). If you're dealing with user input or API data that comes as strings, you might want to parse the value to a number first using parseFloat() or ensure it's rounded to 2 decimal places before passing it to this function to avoid unexpected behavior.
内容的提问来源于stack exchange,提问作者Reece

