1

Let's say the input string is: 1234*(5600-230.831)+1234.56/8456123*25%

The output string needs to have commas added: 1,234*(5,600-230.831)+1,234.56/8,456,123*25%

I have this so far for simple numbers. But is there some way to make it work with complex equations as shown in above example?

private void TextBoxEquation_TextChanging(TextBox sender, TextBoxTextChangingEventArgs args)
{
    try
    {
        int selectionIndex = textBoxEquation.SelectionStart;
        string simpleNum = textBoxEquation.Text.Replace(",", "");
        var value = string.Format("{0:N0}", long.Parse(simpleNum));
        textBoxEquation.Text = value;
        textBoxEquation.SelectionStart = selectionIndex + 1;
    }
    catch { }
}

Basically, as the user types in the equation, the relevant commas need to be added automatically.

EsAMe
  • 305
  • 2
  • 13
  • 1
    You'll have to parse the equation, find all of the numbers, format them appropriately, and reconstruct the equation – canton7 Aug 20 '19 at 13:23
  • 1
    You need to make a CultureInfo that allows number to have comma separated thousands so you can parse the numbers without removing the commas and then output with commas. – jdweng Aug 20 '19 at 13:42

2 Answers2

1

You can use Regex.Replace to identify and replace the relevant parts of the input that need updating.

For example:

var input = @"1234*(5600-230.831)+1234.56/8456123*25%";
var output = Regex.Replace(input, @"(\d{4,}(?:\.{1}\d+){0,1})", (match) => FormatNumber(decimal.Parse(match.Value)));
// 1,234*(5,600-230.831)+1,234.56/8,456,123*25%

FormatNumber looks like this:

private static FormatNumber(decimal input)
{
    var nums = decimal.GetBits(input);
    var decimals = BitConverter.GetBytes(nums[3])[2];
    return input.ToString($"N{decimals}");
} 

Which preserves the precision of the original number while adding the thousand separator (taken from this answer).

steve16351
  • 5,372
  • 2
  • 16
  • 29
0

As others have said, it seems you will need to find all the numbers, format them then reassemble the equation.

One way you may be able to find all the numbers is with a regex such as: [0-9]+(?:\.[0-9]+)?. This should match integers and numbers with a decimal place.

This should match all numbers in the equation. It works for the sample you gave (see: https://regex101.com/r/UaGO0v/1), however it may require some refinement for some edge cases.

Formatting them with commas should be fairly simple, see: https://stackoverflow.com/a/105793/4690605

QTom
  • 1,441
  • 1
  • 13
  • 29