0

I need to format input currency (with no decimal places) to standard way (like $XXX,XXX,XXX,XXX). User can input any of below:

  1. $123
  2. $123,123
  3. $1,123,123
  4. 123,123
  5. 12,123,123
  6. 12312312
  7. 123
  8. $12123123

I have written a Regex through which i can find the pattern needed --> ^\$?[0-9]{1,3}(?:(,[0-9]{3})*|([0-9]{3})*)?$ but I am not able to understand how to write substitute in order to format above examples to $XXX,XXX,XXX,XXX... format (as there are no fixed groups which I can pick).

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
SKS
  • 220
  • 3
  • 12

1 Answers1

5

Instead of regular expressions I suggest parsing and formatting:

  Func<string, string> beautify = (value) => decimal
    .Parse(value,                                        // parse initial value as
           NumberStyles.Currency,                        // currency
           CultureInfo.GetCultureInfo("en-US"))          // of the US
    .ToString("c0",                                      // format as currency (no cents)
               CultureInfo.GetCultureInfo("en-US"));     // of the US 

Demo:

  string[] tests = new string[] {
    "$123",
    "$123,123",
    "$1,123,123",
    "123,123",
    "12,123,123",
    "12312312",
    "123",
    "$12123123",
  };

  string demo = string.Join(Environment.NewLine, tests
    .Select(test => $"{test,-15} -> {beautify(test)}"));

  Console.Write(demo);

Outcome:

$123            -> $123
$123,123        -> $123,123
$1,123,123      -> $1,123,123
123,123         -> $123,123
12,123,123      -> $12,123,123
12312312        -> $12,312,312
123             -> $123
$12123123       -> $12,123,123
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • Interresting ! I came with a solution using `int.Parse(Regex.Replace(input, "[^0-9]", ""));` to strip any non numeric character and then `String.Format("{0:n0}", num);` (but that works only for integers) – Cid Sep 27 '19 at 07:43
  • @Cid: Why should we reinvent the wheel when we let .net do its work (parsing and formatting)? I doubt if we should strip *any non numeric character*; what if I have `"+7(999)55-777-888"` input (typical user error, he put phone number isntead of currency)? Let me have an *exception thrown* instead of being charged for *8 billion* – Dmitry Bychenko Sep 27 '19 at 07:56