Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.Format an integer to use a thousands separator with decimal value in danish culture

Tags:

c#

asp.net

I have a string totalPRice which holds a value like this 1147,5 I want two things.
1)round the value so that there is always two digits after ,
2)Implement thousands separator in this string, So that final out put will be some thing like this 1.147,50
I have tried some thing like this

String.Format("{0:0.00}", totalPRice)

It does my first requirement correctly by producing an output 1147,50. But I am way behind in my second requirement. Can any one tell me how I can achieve this?

Note: In danish culture . stands for , and , stands for .

like image 725
None Avatar asked Dec 05 '13 09:12

None


People also ask

How can I parse a string with a comma thousand separator to a number?

We can parse a number string with commas thousand separators into a number by removing the commas, and then use the + operator to do the conversion. We call replace with /,/g to match all commas and replace them all with empty strings.

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

To parse a string with commas to a number: Use the replace() method to remove all the commas from the string. The replace method will return a new string containing no commas.


2 Answers

You can refer to Standard Numeric Format Strings and use

string.Format("{0:N2}", 1234.56)

You may also specify the culture manually, if danish is not your default culture:

var danishCulture = CultureInfo.CreateSpecificCulture("da-DK");
string.Format(danishCulture, "{0:N2}", 1234.56);

see MSDN Reference for CultureInfo

like image 200
NobodysNightmare Avatar answered Sep 19 '22 19:09

NobodysNightmare


You should create a culture-specific CultureInfo object and use it when converting the number into a string. Also, you can set the default culture for your whole program.

Then, your code will look like this:

// create Dennmark-specific culture settings
CultureInfo danishCulture = new CultureInfo("da");

// format the number so that correct Danish decimal and group separators are used
decimal totalPrice = 1234.5m;
Console.WriteLine(totalPrice.ToString("#,###.##", danishCulture));

Note that . and , in the formatting string are specified opposit as you want. This is because they identify decimal and group separators, and are replaced with the correct culture specific-ones.

like image 43
Ondrej Tucny Avatar answered Sep 20 '22 19:09

Ondrej Tucny