0

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?

CrazyEight
  • 147
  • 1
  • 18
  • I don't think this is a duplicate of https://stackoverflow.com/questions/13477689/find-number-of-decimal-places-in-decimal-value-regardless-of-culture. This question is about counting digits in strings, the linked question was about retrieving the `Decimal` type's internal decimal places count. (Or at least that's what the answers are about.) – relatively_random Jul 10 '23 at 07:27
  • The [How to extract decimal number from string in C#](https://stackoverflow.com/q/3575331/3832970) thread explains how to extract an int/float value with both commas or dots. See https://regex101.com/r/2TeD48/1 – Wiktor Stribiżew Jul 10 '23 at 07:36
  • Just search for `(?<=[,.])\d+` and count the number of characters https://regex101.com/r/Wlx5xl/1 – CAustin Jul 10 '23 at 07:41

0 Answers0