0

I have two different queries for which I have

(535.00).ToString("C", CultureInfo.CreateSpecificCulture(Configuration.UICulture));

but what I want is if there is 0 after decimal I don't want to show decimal digit and if there is something else for example 535.50 then only I want to show the decimal so for that I am out with the solution decimal.ToString("G29") and now I am not able to do that since I am already using culture format for $ sign and the value is converted into string.

So, I want to use both the formats in string.ToDecimal("G29") and string.ToString("C", CultureInfo.CreateSpecificCulture(Configuration.UICulture)) since I want the resultant value to be either 535$ or 535.50$.

You can either suggest me how to use multiple decimal to string formatted or you can suggest me some better solution if you have. I will appreciate your answer.

Thanks

Kovid Purohit
  • 258
  • 1
  • 4
  • 15

1 Answers1

0

I would use the n2 numeric format to get two decimal digits, then remove any .00 part by making sure to use the right decimal separator and finally add the currency symbol.

decimal input = 535.00m; // or 535.50m
var cultureInfo = CultureInfo.CreateSpecificCulture(Configuration.UICulture);
string nullDecimal = numberFormat.NumberDecimalSeparator + "00";
string output = input.ToString("n2", cultureInfo).Replace(nullDecimal, "") +
    cultureInfo.NumberFormat.CurrencySymbol;

Displays 535$ or 535.50$.

You could also use the currency format directly

string output = input.ToString("c2", cultureInfo).Replace(nullDecimal, "")

but this will put the $ sign before the number I think.

Note that n2 produces thousands (group) separators (e.g. 1,535.50$). Use f2 instead, if you don't want this.

The c format produces as many digits as specified in NumberFormatInfo.CurrencyDecimalDigits. So, you may want to use this one and to get the number of 0 decimals to remove dynamically

decimal[] inputs = { 1535.00m, 1535.50m };
foreach (decimal input in inputs) {
    var cultureInfo = CultureInfo.CreateSpecificCulture(Configuration.UICulture);
    NumberFormatInfo numberFormat = cultureInfo.NumberFormat;
    string nullDecimal = numberFormat.NumberDecimalSeparator +
        new string('0', numberFormat.CurrencyDecimalDigits);
    string output = input.ToString("c", cultureInfo).Replace(nullDecimal, "");

    Console.WriteLine(output);
}

For en-US, this prints:

$1,535
$1,535.50

for ja-JP:

¥1,535
¥1,536
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • 1
    The currency format controls the punctuation of the number (commas or decimal points or spaces) the currency symbol and the location of the currency symbol based on the culture. Some cultures put the currency symbol at the end of the number, so using the currency format would definitely be the safer thing to use. – TJ Rockefeller Jul 12 '21 at 16:15
  • @TJRockefeller, yes. See my final solution. – Olivier Jacot-Descombes Jul 12 '21 at 16:24