不使用NumberFormatter为USD价格字符串添加千位分隔符的方法
Absolutely! You can add thousands separators to your price string without relying on NumberFormatter—it just requires some straightforward string manipulation. Let’s walk through two practical approaches tailored to your use case:
1. Manual String Manipulation (Reverse & Insert Commas)
This method breaks the price into integer and decimal parts, then adds commas by reversing the integer portion to count from the right, inserting separators every three digits before reversing it back.
Here’s a Swift implementation you can drop in:
func formatUSDPrice(finalPrice: Double) -> String { // Start with your existing two-decimal format let rawPrice = String(format: "%.2f", finalPrice) // Split into integer and decimal components let priceComponents = rawPrice.components(separatedBy: ".") guard let integerPart = priceComponents.first, let decimalPart = priceComponents.last else { return "$\(rawPrice)" } // Process the integer part to add commas var formattedInteger = "" let reversedDigits = integerPart.reversed() for (index, digit) in reversedDigits.enumerated() { // Insert a comma every 3 digits (skip the first position) if index != 0 && index % 3 == 0 { formattedInteger += "," } formattedInteger.append(digit) } // Reverse back to get the correct digit order formattedInteger = String(formattedInteger.reversed()) // Combine all parts with the dollar sign return "$\(formattedInteger).\(decimalPart)" }
How it works:
- We start with your existing logic to get a two-decimal string
- Split the string to handle whole numbers and cents separately
- Reverse the integer digits to easily count from the right, inserting commas every three characters
- Reverse the integer part back to its original order and combine with the decimal part and dollar sign
2. Regular Expression Replacement
If you prefer a more concise approach, a regex can find and replace groups of three digits (from right to left) with a comma-separated version automatically.
Here’s the regex-based implementation:
func formatUSDPriceWithRegex(finalPrice: Double) -> String { let rawPrice = String(format: "%.2f", finalPrice) let priceComponents = rawPrice.components(separatedBy: ".") guard let integerPart = priceComponents.first, let decimalPart = priceComponents.last else { return "$\(rawPrice)" } // Regex pattern to target digits that need a comma before them let commaRegex = try! NSRegularExpression(pattern: "(\\d)(?=(\\d{3})+(?!\\d))", options: []) let integerRange = NSRange(location: 0, length: integerPart.utf16.count) // Replace matches to insert commas in the right spots let formattedInteger = commaRegex.stringByReplacingMatches( in: integerPart, options: [], range: integerRange, withTemplate: "$1," ) return "$\(formattedInteger).\(decimalPart)" }
How the regex works:
(\d)captures a single digit(?=(\d{3})+(?!\d))is a positive lookahead that checks if the captured digit is followed by one or more groups of three digits, with no extra digits after those groups. This ensures commas are only added in the correct positions (from the right).
A Quick Side Note:
While these methods work perfectly for your needs, keep in mind that NumberFormatter is Apple’s recommended tool for currency formatting—it handles edge cases like negative prices, locale-specific variations, and more with minimal code. But if you’re set on avoiding it, the above approaches will get the job done reliably.
内容的提问来源于stack exchange,提问作者Wizzardzz

