4

I was trying to format a number 173910234.23 to something like 17,39,10,234.23. Here only the first thousand separator is after three digits. But after that all separators (,) are after two digits. I have tried the following -

double d = 173910234.23;
Console.WriteLine(string.Format("{0:#,##,##,###.00}", d));

but it gives output with comma after every three digits, 173,910,234.23

How can I achieve the format 17,39,10,234.23 using string.Format?

2
  • Are you sure? you need 17,39,10,234.23 or 1,73,91,02,34.23 Commented Nov 23, 2013 at 8:43
  • I need 17,39,10,234.23. I am sure. Commented Nov 23, 2013 at 8:43

2 Answers 2

8

Number groups are defined by NumberGroupSizes property of NumberFormatInfo. So modify it accordingly and just use N format specifier.

double d = 173910234.23;
var culture = new CultureInfo("en-us", true)
{
    NumberFormat =
    {
        NumberGroupSizes = new int[] { 3, 2 }
    }
};
Console.WriteLine(d.ToString("N", culture));

This outputs

17,39,10,234.23


Thanks @Rawling and @Hamlet, for shedding light on this. Now OP gets expected output and me too learned something..

Sign up to request clarification or add additional context in comments.

6 Comments

Hey, I've never hear of NumberGroupSizes before now, but if you make it new int[] { 3, 2 } it should do exactly what OP wants.
After setting NumberGroupSizes you can just use standard number format as d.ToString("N", culture)
@HamletHakobyan yup, you're right I just copied from question. Didn't realized whether it is useful or not.
Community making this answer more and more good.. Thank you all.. :)
I didn't know about NumberGroupSizes. But I knew that there has to be something like this :).
|
0
string output = null;    
string num = Number.ToString();
for(int i = 0; i < num.Length; ++i)
 {
        switch(i)
        case 2:
        case 4:
        case 6:
            output += ",".ToString() + num[i].ToString(); 
        break;
        default:
            output += num[i].ToString(); 
        break:
 }

If you want to use a different number, replace the numbers with the positions of the numbers where you want to insert the comma before (remember the first character of a string has the position of 0)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.