Quoc Nguyen
Quoc Nguyen

Reputation: 360

String format number with three sections as String.Format(“{0:$#,##0.00;($#,##0.00);Zero}”, value);

I'm implementing string format number with three sections as

DataFormatString="{}{0:$#,##0.00;($#,##0.00);''}"

i.e:

input 120 result $120.00
input -120 result ($120.00)
input 0 result ''

the problem is the dollar sign is hard-coded and I want my app to globalization. I tried some thing like this:

DataFormatString="{}{0:C;C;''}"

but it doesn't help.

Upvotes: 0

Views: 2266

Answers (3)

Soner Gönül
Soner Gönül

Reputation: 98810

As far as I know, there is no direct format to supply that 3 results you want for those inputs.

For first two format, you can use The "C" format specifier with en-US culture (which has $ as a CurrencySymbol) using 2 as a precision specifier like;

(120).ToString("C2", CultureInfo.GetCultureInfo("en-US"))  // $120.00
(-120).ToString("C2", CultureInfo.GetCultureInfo("en-US")) // ($120.00)

But for 0, this generates $0.00 which is not what you want.

As a better solution, check Enigmativity's answer instead which handles 0 value as well.

Upvotes: 1

shree.pat18
shree.pat18

Reputation: 21757

You can use the overload of string.Format with IFormatProvider like so:

string DataFormatString="{0:C}";
string output = string.Format(CultureInfo.CreateSpecificCulture("culture"),DataFormatString,input)

Demo

However, as Soner Gonul observes, this still won't generate '' as output for 0.

Upvotes: 1

Enigmativity
Enigmativity

Reputation: 117124

Perhaps try taking this approach:

var DataFormatString="$#,##0.00;($#,##0.00);''";

var amount = 1342.56m;

var formatted =
    amount
        .ToString(DataFormatString)
        .Replace("$", CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol);

The only downside is that it won't correctly place the currency symbol at the end of the number if that's the standard for that currency.

Upvotes: 3

Related Questions