Alex Awad Alex Awad - 4 months ago 20
C# Question

C# number different formats

I am working on a project that requires to parse data from a file and store it to MySQL database
the file has the following string in multiple formats

Ava. bytes -> 147.258.369
Ava. bytes -> 147.258.369,5
Ava. bytes -> 147,258,369
Ava. bytes -> 147,258,369.5


what is the best way to convert any of these formats to

Ava. bytes -> 147.258.369 => 147258369.0
Ava. bytes -> 147.258.369,5 =>147258369.5
Ava. bytes -> 147,258,369 => 147258369.0
Ava. bytes -> 147,258,369.5 =>147258369.5


thank you!

Answer

You can use a regular expression to remove any dot or comma that is followed by three digits, and a string replace to substitute the final decimal comma for a period if there is one:

string n = "147.258.369,5";
var r = new Regex(@"[.,](?=\d{3})");
string n2 = r.Replace(n, "").Replace(',', '.');

Edit:

The string is then in InvariantFormat if you want to parse it to a decimal (but presumably you want the string since the .0 is important.)

To include the final .0:

if (n2.Length < 2 || n2[n2.Length - 2] != '.')
{
    n2 = n2 + ".0";
}