Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert number into culture specific

I have a number like 202667.4. I want to convert this to number based on culture.

For Ex:

In "de"(German) the number should be in 202.667,40.

Any help will be greatly appreciated.

Thanks.

like image 680
Manikandan Ram Avatar asked Nov 16 '17 07:11

Manikandan Ram


2 Answers

If you want to represent existing number (say, double) in culture specific format, try formatting:

https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings

double source = 202667.4;

// "n"  - ... group separators, and a decimal separator with optional negative sign  
// "de" - German culture
string result = source.ToString("n", CultureInfo.GetCultureInfo("de"));

Console.WriteLine(result);

Outcome

202.667,40

If you are given a string and you want a number, put Parse (TryParse):

string data = "202.667,40";

double result = double.Parse(data, CultureInfo.GetCultureInfo("de"));

Console.WriteLine(data.ToString(CultureInfo.InvariantCulture));

If you don't want to specify the culture each time you work with formatting, you can set the culture as a current one:

CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("de");

...

double source = 202667.4;

Console.WriteLine($"{source:n}");
like image 150
Dmitry Bychenko Avatar answered Nov 03 '22 07:11

Dmitry Bychenko


You can use Culture info while parsing number into German format

Try with this approach:

string.Format(System.Globalization.CultureInfo.GetCultureInfo("de-DE"), "{0:000,000.00}", <your number>)

for example:

 string result = string.Format(System.Globalization.CultureInfo.GetCultureInfo("de-DE"), "{0:000,000.00}", 202667.4)
like image 1
Prasad Telkikar Avatar answered Nov 03 '22 05:11

Prasad Telkikar