In my .NET 6 application, i have many different numerical values that can appear in different representations and I would like to write a method that counts the decimal places.
Some of the numbers are like
8,8386 %
370878439,39 €
370,88 Mio. €
375962902,92 €
-375,963 Mio. €
+25,58 %
371 €
+370,88 Mio.
€ 93,8 million
290.5 million
12.8
100
8,8386 %
17226720,27 €
371 million €
375.96 €
I can't just parse the strings to decimals as this will not work with the different trailing parts like Mio.
, million
etc...
So i thought about removing all non-numeric parts of the numbers, then just build a substring after the comma and count the length of that substring.
public int CountDecimals(string input)
{
// Remove any non-digit characters except for decimal points and commas
string pattern = @"[^0-9.,]+";
string numericValue = Regex.Replace(input, pattern, "");
// Remove any thousand separators and convert commas to dots for decimal points
numericValue = numericValue.Replace(".", ",");
return numericValue.Substring(numericValue.LastIndexOf(',') + 1).Length;
}
The problem here is, that the regular expression [^0-9.,]+
does not match the last .
in for example 370,88 Mio. €
so it becomes 370,88.
what will then become 370,88,
so the final output will be 0
.
Is there a better regular expression for extracting those numbers or even a better solution for counting those digits?