ahmed
ahmed

Reputation: 45

Using CultureInfo in order to replace USD symbol with -

I am currently using this code in order to remove the US symbol and make the number appear as a negative

The code that I am using is:

public strNegative = "-";

string Result = TrnAmount
  .ToString("C3", new CultureInfo("en-US"))
  .Replace("$", strNegative);

However the result is appearing with brackets:

Result = "(-5)"

When required format is

Result = "-5"

Upvotes: 1

Views: 821

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Technically, you can create you own CultureInfo, e.g.

  // Same as US
  CultureInfo myUSCulture = new CultureInfo("en-US", true);

  // Except dollar sign removed
  myUSCulture.NumberFormat.CurrencySymbol = "";
  // and negative pattern changed: "-value" instead of "(value)"
  myUSCulture.NumberFormat.CurrencyNegativePattern = 1;

Then use it:

  decimal TrnAmount = -123456789.987M;

  Console.WriteLine(TrnAmount.ToString("C3", myUSCulture)); // exactly 3 digits after .
  Console.WriteLine(TrnAmount.ToString("C2", myUSCulture)); 
  Console.WriteLine(TrnAmount.ToString("C0", myUSCulture)); // no floating point

Outcome:

  -123,456,789.987
  -123,456,789.99  // rounded
  -123,456,790     // rounded

Upvotes: 1

Renatas M.
Renatas M.

Reputation: 11820

Welcome. To get negative number just multiply number by -1. Then use N3 as a string format if you want to get general number and not a currency format.

float TrnAmount = 2.5684155f;
string result = (-1 * TrnAmount).ToString("N3");
Console.WriteLine(result); //This will give you -2.568 as a result

Upvotes: 4

Related Questions