2

I'm trying to format number into amount format using regex like below.

  var input = "1234567.00"
  var pattern = @"\d(?=(\d{3},?)+\.)";
  var replacement = "$$$&,";

  var output = Regex.Replace(input, pattern, replacement);

Which gives me $1,23$4,567.00 (extra $).

I want like below

Input:1234567.00 or 1234,567.00 or 1234567 should return $1,234,567.00

Please suggest correct one.

Prasad Kanaparthi
  • 6,423
  • 4
  • 35
  • 62
  • what you want get ? as result? – SL5net Sep 07 '18 at 04:31
  • @SL5net Updated. Please check – Prasad Kanaparthi Sep 07 '18 at 04:35
  • 3
    How using regex? you don't. Parse it to a decimal and use the string formatting options to convert it to a string in currency format... – Jeff Mercado Sep 07 '18 at 04:40
  • 1
    Why do yo not use ToString("C") and check https://stackoverflow.com/questions/45600344/c-sharp-tostringc-converting-the-decimal-to-currency-value-pound-instead-of – Niranjan Singh Sep 07 '18 at 04:51
  • 2
    "if all you have is a regex, everything looks like a string operation." – Corak Sep 07 '18 at 04:54
  • my first prototype: `[^,\.\d](\d{3}?)(\d+,?\d*)([\.](\d{2}))?\b` to `$1,$2.$3` But you need to programm a line with to add you .00 in some cases https://imgur.com/a/tWvvVPi – SL5net Sep 07 '18 at 04:56
  • second prototype `[^,\.\d](\d+?,?\d*?)(\d{3})?([\.](\d{2}))?\b` https://imgur.com/a/tWvvVPi i think it could not be done with pure regEx. needs additional a little programmed in c# – SL5net Sep 07 '18 at 05:06

3 Answers3

6

Take a look at MSDN documentation sample:

var input = "1234567.00";
NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat;
var currencyValue = decimal.Parse(input);
var output = currencyValue.ToString( "C", nfi );
Access Denied
  • 8,723
  • 4
  • 42
  • 72
2

Access Denied has the correct answer to your actual (non-regex) problem. This isn't something you can easily, or even should do with regex. There are limits. It's like asking »How can I establish a database connection with Console.WriteLine?« It's that kind of nonsensical.

You can do so in one replacement, if you absolutely, desperately have to:

Regex.Replace(input, @"^|(\d{3}(?=(\d{3})*(\.|$)))", m => m.Value == "" ? "$" : "," + m.Value);

This will add a $ in the beginning, and insert commas accordingly. It will also ignore regional settings, currency symbol and other things that the other answer gets right.

Joey
  • 344,408
  • 85
  • 689
  • 683
-1

Maybe something like this:

//.replace(/(\d)(?=(\d{3})+\b)/g, "$1,").replace(/(.*\d)/g, '$$$1');
var input = "1234567.00";

var commaPattern = @"(\d)(?=(\d{3})+\b)";
var commaReplacement = "$1,";
var output = Regex.Replace(input, commaPattern, commaReplacement);

var dollarPattern = @"(.*\d)";
var dollarReplacement = "$$$1";
output = Regex.Replace(output, dollarPattern, dollarReplacement);

Gives $1,234,567.00

noxsoul
  • 66
  • 5