Home > database >  How to change the position of the currency symbol relative to a number?
How to change the position of the currency symbol relative to a number?

Time:10-20

Is it possible to change the place of '$' char in a string according to its relative position to a number?

Example:

string input = "the price is 18$. It increased to 24.50$ ."

output = "the price is $18. It increased to $24.50 ."

CodePudding user response:

You can use Regex for this:

using System.Text.RegularExpressions;
// ...

string output = Regex.Replace(input, @"\b(\d (?:\.\d )?)\$", "$$$1");

Regex demo | C# demo

Regex pattern details:

  • \b - Word boundary to make sure it's a standalone number.
  • ( - Start of capturing group #1.
    • \d - One or more digits.
    • (?: - Start of a non-capturing group.
      • \.\d - A dot followed by one or more digits.
    • ) - Close the non-capturing group.
    • ? - Make the previous group optional.
  • ) - Close group #1.
  • \$ - Match a dollar sign.

Replacement details:

  • $$ - Dollar sign.
  • $1 - Whatever was matched in group #1 (i.e., the number).

References:

  • Related