Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a number with commas and decimals in C# (asp.net MVC3)

I need to display a number with commas and a decimal point.

Eg: Case 1 : Decimal number is 432324 (This does not have commas or decimal points).
Need to display it as: 432,324.00.
Not: 432,324

Case 2 : Decimal number is 2222222.22 (This does not have commas).
Need to display it as: 2,222,222.22

I tried ToString("#,##0.##"), but it is not formatting it correctly.

like image 694
Krishan Avatar asked Apr 16 '13 11:04

Krishan


People also ask

How do you add commas with decimals?

Commas in NumbersThey are placed every three decimal places to the left of the decimal point, which is marked with a period (full stop). For example: 123,456.789.

How do you convert a number to a comma separated string?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do I get 6 decimal places in C#?

Use N6 as the numeric format string.

Can I use decimal in C#?

Some languages, such as C#, also support the conversion of Decimal values to Char values.


2 Answers

int number = 1234567890; Convert.ToDecimal(number).ToString("#,##0.00"); 

You will get the result 1,234,567,890.00.

like image 141
Roys Avatar answered Sep 20 '22 13:09

Roys


Maybe you simply want the standard format string "N", as in

number.ToString("N") 

It will use thousand separators, and a fixed number of fractional decimals. The symbol for thousands separators and the symbol for the decimal point depend on the format provider (typically CultureInfo) you use, as does the number of decimals (which will normally by 2, as you require).

If the format provider specifies a different number of decimals, and if you don't want to change the format provider, you can give the number of decimals after the N, as in .ToString("N2").

Edit: The sizes of the groups between the commas are governed by the

CultureInfo.CurrentCulture.NumberFormat.NumberGroupSizes 

array, given that you don't specify a special format provider.

like image 42
Jeppe Stig Nielsen Avatar answered Sep 18 '22 13:09

Jeppe Stig Nielsen