Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

c#-4.0

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 the string with . and changing commas in the string to periods and then joining 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 clumsy. Any better methods?

like image 345
naveen Avatar asked Apr 23 '12 13:04

naveen


Video Answer


4 Answers

The correct way to do this (correct as in not string-mashing) is to use the CultureInfo for the culture you're formatting for. Looks like you're after the italian culture it-IT:

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

Live example: http://rextester.com/ARWF39685

Note that in a format string you use , to mean "number group separator" and . to indicate "decimal separator" but the culture info replaces that with the correct separator for the culture - in terms of Italian culture they are exactly reversed (. is the group separator and , is the decimal separator).

like image 81
Jamiec Avatar answered Oct 05 '22 23:10

Jamiec


If there is a symbol that does not appear anywhere in your string, say, '$', you can do it like this:

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

To be sure, this is suboptimal in terms of CPU cycles, but it does the trick in terms of staying on a single line.

like image 34
Sergey Kalinichenko Avatar answered Oct 05 '22 23:10

Sergey Kalinichenko


string value = "12,345,678.90";
value = string.Join(".", value.Split(',').Select(s => s.Replace(".", ",").ToArray());
like image 45
Nikhil Agrawal Avatar answered Oct 05 '22 23:10

Nikhil Agrawal


you have

string value = "12,345,678.09";
value = value.replace(",", "_").replace(".", ",").replace("_", ".")
like image 27
Ali Adravi Avatar answered Oct 06 '22 01:10

Ali Adravi