Reputation:
When we convert like String.Format("{0:C}", 126.45)
it returns $126.45
but if we convert like String.Format("{0:C}", -126.45)
it returns ($126.45)
Why negative conversion return braces? What to do if we don't want this braces?
Upvotes: 2
Views: 10769
Reputation: 448
Swift 5 Here is best solution if you get after formate this kind of value (-300)
extension Double {
static let twoFractionDigits: NumberFormatter = {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.minimumFractionDigits = 2
formatter.maximumFractionDigits = 2
formatter.currencySymbol = "$"
formatter.currencyCode = "USD"
formatter.numberStyle = .currency
formatter.usesGroupingSeparator = true
return formatter
}()
var formatted: String {
return Double.twoFractionDigits.string(for: self) ?? ""
}
}
Upvotes: 1
Reputation: 2874
Why don't you try something like:
String.Format("{0:$#,##0.00}", -126.45)
According to the documentation here a format of "{0:C1}" or "{0:C2}" should work, but for some strange reason it is not..
Another approach could be setting the CultureInfo:
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.CurrencyNegativePattern = 1;
string s = string.Format(culture, "{0:c}", -126.45);
Reference here
Upvotes: 11
Reputation: 20320
It does parentheses, because that's the standard on whatever CultureInfo
you are using.
Never done it myself but the make up of the format is controlled by the current NumberFormatInfo
instance.
If you figure it out, answer your own question, and I'll plus you
Upvotes: 0
Reputation: 5018
In the en-US locale, parentheses are used to denote negative values. Visually scanning a long column of numbers, many people find it easier to see the negatives. Often it's the negative values that are of most concern (oops! my checking account balance is overdrawn).
To get different formatting behavior, you can change your locale, or you can change your format specifier to something like F.
Upvotes: 0