Is there a possibility to use NSNumberFormatter for NSNumber formatting together with plural rules in stringsdict?
I need to have the next with formatted numbers (separate thousands). If I format the number using NSNumberFormatter - I receive NSString and I can't use plural rules anymore, because iOS can't understand whether phrase is for single or plural noun from NSString.
"1 Workout" for single
"1,732,123 Workouts" for plural
NSNumberFormatter* numberFormatter = ...;
[NSString stringWithFormat:NSLocalizedString(@"%@ Workouts!", @"n Workout(s)"), [numberFormatter stringFromNumber:value]]
You can pass number and formatted string (2 arguments) into NSLocalizedString
The basic idea is to use the number to control plural rule but use the formatted string to display.
I'm using Decimal
in Swift as an example:
let number: Decimal = 13456
let formatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.groupingSeparator = ","
return formatter
}()
let formattedNumberString = formatter.string(from: number as NSDecimalNumber) ?? "-" // "13,456"
let format = NSLocalizedString(
"workouts",
comment: "arg1 is for number, arg2 is for formatted string"
)
let resultString = String.localizedStringWithFormat(
format,
number as NSDecimalNumber,
formattedNumberString
)
In the Localizable.stringsdict,you can do:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>workouts</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%1$#@number@</string>
<key>number</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>@</string>
<key>one</key>
<string>%2$@ Workout!</string>
<key>other</key>
<string>%2$@ Workouts!</string>
</dict>
</dict>
</dict>
</plist>
The resultString
is 13,456 Workouts!
in this example. If you change number = 1
, the resultString
will be 1 Workout!
After some research I found, that I can separate thousands in number without NSNumberFormatter, just using localizedStringWithFormat. And it also gives me the possibility to use plural rules.
[NSString localizedStringWithFormat:NSLocalizedString(@"%@ Workouts!", @"n Workout(s)"), value]
Localizable.stringsdict
...
<key>%@ Workouts</key>
<dict>
<key>NSStringLocalizedFormatKey</key>
<string>%#@Workouts@</string>
<key>Workouts</key>
<dict>
<key>NSStringFormatSpecTypeKey</key>
<string>NSStringPluralRuleType</string>
<key>NSStringFormatValueTypeKey</key>
<string>@</string>
<key>one</key>
<string>%@ Workout!</string>
<key>other</key>
<string>%@ Workouts!</string>
</dict>
</dict>
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With