How to convert a comma in a period and period to a comma in one line

I have a number like this 12,345,678.09 which I would like to convert to 12.345.678,09 I am thinking of splitting a string with . and changing the commas in the line for periods, and then adding them with a comma.

 string value = "12,345,678.09"; string[] parts = value.Split(new char[]{'.'}); string wholeNumber = parts[0].Replace(",", "."); string result = String.Format("{0},{1}", wholeNumber, parts[1]); 

I feel this method is very awkward. Any best practices?

+6
source share
5 answers

The correct way to do this (correction, as in non-game) is to use CultureInfo for your culture formatting for. It looks like you are after the Italian it-IT culture:

 var num = 123456789.01; var ci = new CultureInfo("it-IT"); Console.WriteLine(num.ToString("#,##0.00",ci)); //output 123.456.789,01 

Real-time example: http://rextester.com/ARWF39685

Note that in the format string you use , to indicate the "separator of groups of numbers" and . to indicate a "decimal separator", but the culture information replaces this with the correct separator for the culture - from the point of view of Italian culture they are exactly reversed ( . is the group separator, and , is the decimal separator).

+8
source

If there is a character that is not displayed anywhere on your line, say, '$' , you can do it like this:

 parts[0].Replace(",", "$").Replace(".", ",").Replace("$", "."); 

Of course, this is suboptimal in terms of processor cycles, but it does the trick in terms of staying on one line.

+9
source
 string value = "12,345,678.90"; value = string.Join(".", value.Split(',').Select(s => s.Replace(".", ",").ToArray()); 
+4
source

you have

 string value = "12,345,678.09"; value = value.replace(",", "_").replace(".", ",").replace("_", ".") 
+1
source

You can go with:

 string newString = Convert.ToDouble(oldString).ToString("#,0.##", new CultureInfo("de-DE")); 

More details here .
All this in one line, as you like, and the recommended path.
You can also use other cultures or CultureInfo.CurrentCulture to show the numbers as the user uses to view them. If it is on an Italian window, it will have CurrentCulture == "it-IT" and the number format accordingly. CurrentCulture is probably what you are looking for, I guess correct me when I'm wrong.
Edit: according to the format of Jamiecs comments, this method does not work on lines, so I added a conversion. But keep in mind: if the conversion does not work, it may throw an exception. Therefore, it is better to do this in a few lines and use Double.TryParse () or something like that.

0
source

Source: https://habr.com/ru/post/913933/


All Articles