Bhavesh Vekariya
Bhavesh Vekariya

Reputation: 17

Custom number group (thousand separator) for 1000,000 format in c#

My code is as below I am trying to get custom grouping on number example: 1000000 should be 1000,000

I have tried many search result that allows thousand separator and also custom grouping but each one gives a result like 10,00,000

decimal value = decimal.Parse(txtamount.Text.Trim());
txtamount.Text = value.ToString("#,###0");

In this code I have tried below code also

txtamount.Text = String.Format("{0:n0}", value);
txtamount.Text = value.ToString("#,##0", new System.Globalization.CultureInfo("en-US"));
txtamount.Text = value.ToString("0,0.0",CultureInfo.InvariantCulture); //-->1,000,000.0

It is not a normal thousand separator grouping of a number. I am trying to get output in a format 1000,000

Upvotes: 1

Views: 399

Answers (3)

Hans Kesting
Hans Kesting

Reputation: 39329

To just have one grouping separator, you can use this:

// create a writable copy of the culture of your choice
var ci = (CultureInfo)CultureInfo.GetCultureInfo("en-us").Clone();

// change the group sizes: the first one after 3 digits (counting backwards)
// NO second (third, ..) one!
ci.NumberFormat.NumberGroupSizes = new[]{3,0};

// and use it 
// the , in the format means "use a group separator", it does NOT specify a position
var millionString1 = 1_000_000.ToString("#,#", ci); // 1000,000
var millionString2 = 1_000_000.ToString("N0", ci); // also 1000,000

But do note that 10 million would now become 10000,000.

See docs.

Upvotes: 2

Slai
Slai

Reputation: 22876

Doesn't seem possible without a custom formatter, but the comma can be inserted after. For example :

string value = "1234567.890"
string result = Regex.Replace(value, @"(\d+)(\d\d\d)", "$1,$2");  // result = "1234,567.890"

Upvotes: 0

Lowkey
Lowkey

Reputation: 836

Since it's a custom format, you'll need to escape your comma ,

string.Format("{0:####\\,###}",value)

Upvotes: 0

Related Questions