String Format to show a currency with two decimal places only if there are decimal numbers (.net)

Silverlight 4 / C #: I have a label showing a number formatted in the currency (with 2 decimal places) of the stream culture, e.g.

25 shows that $ 25.00 and 25.01 show as $ 25.01

For this, I use "StringFormat = C2". My problem is that ... I want to show only 2 decimal places, if there are decimal places. eg.

25 should show that January 25th and 25th should be displayed as $ 25.01

With a normal number, I would use # - for example. #. ## and what suppresses decimal places if they do not exist, but then I won’t get the currency symbol. C2. ## does not work.

Any suggestions please? (Hard currency symbol is not an option)

+3
source share
2 answers

Check if the decimal fractional element contains a fractional element and returns a different representation depending on the result:

public string GetFormatStringForDecimal(myDec){
    return (Decimal.Ceiling(myDec) > myDec) ? "C2" : "C0";
}

This function will return a format string for your decimal as indicated in your question.

+4
source
decimal value = 1603.42m;
var temp = string.Empty;
if (Decimal.Floor(value) < value) //means value is with decimal part
    temp = value.ToString("C2", new CultureInfo("en-US"));
else
    temp = value.ToString("C0", new CultureInfo("en-US"));
return temp;

FBTMoVGogot

+1
source

Source: https://habr.com/ru/post/1754008/


All Articles