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?
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).
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.
string value = "12,345,678.90";
value = string.Join(".", value.Split(',').Select(s => s.Replace(".", ",").ToArray());
you have
string value = "12,345,678.09";
value = value.replace(",", "_").replace(".", ",").replace("_", ".")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With