Kendo Grid数字格式化:空格千分位分隔符+两位小数实现
Solution for Kendo Grid Number Formatting (Space as Thousands Separator, 2 Decimal Places)
Hey there! Let's fix up that Kendo Grid column to format numbers exactly how you want it—with spaces as thousands separators, two decimal places, plus handling zeros and negative numbers with red styling. Here's a straightforward approach:
Step 1: Create a Reusable Formatting Function
First, make a helper function to handle the number formatting. This keeps your code clean and lets you reuse it across other columns if needed:
function formatNumberWithSpace(num) { // Handle null/undefined values to avoid errors if (num == null) return ""; // Use native Intl.NumberFormat for reliable formatting return new Intl.NumberFormat('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2, groupingSeparator: ' ', useGrouping: true }).format(num); }
This function does exactly what you need:
- Forces two decimal places (even if the number has fewer, it'll add trailing zeros)
- Uses a space as the thousands separator
- Automatically rounds numbers (e.g., 125895456.8942 becomes 125 895 456.89)
Step 2: Update Your Column Template
Now integrate this function into your existing column template logic. We'll keep your existing rules for zeros and negative number styling, but swap out the raw number with our formatted version:
columns: [ { field: "sumStartDebit", title: "Debit", width: "130px", template: function (dataItem) { const debitValue = dataItem.sumStartDebit; // Return empty string for zero values if (debitValue === 0) { return ""; } const formattedDebit = formatNumberWithSpace(debitValue); // Apply red color for negative numbers if (debitValue < 0) { return `<span style='color:red'>${formattedDebit}</span>`; } // Default styling for positive numbers else { return `<span>${formattedDebit}</span>`; } } }, // Add your other columns here... ]
How It Works
- Zero Values: If
sumStartDebitis 0, the template returns an empty string as you wanted. - Negative Numbers: Formatted values get wrapped in a red
<span>to stand out. - Positive Numbers: Cleanly formatted with spaces and two decimals, displayed in default styling.
- Edge Cases: The helper function handles
nullorundefinedvalues gracefully, so you won't get unexpected errors if the data has missing values.
Example Outputs
- Input:
125895456.8942→ Output:125 895 456.89 - Input:
-12345.678→ Output:<span style='color:red'>-12 345.68</span> - Input:
0→ Output:""
内容的提问来源于stack exchange,提问作者Oscar Dominguez Navarrete
相关产品推荐
相关产品推荐

