I have got a price field to display which sometimes can be either 100 or 100.99 or 100.9, What I want is to display the price in 2 decimal places only if the decimals are entered for that price , for instance if its 100 so it should only show 100 not 100.00 and if the price is 100.2 it should display 100.20 similarly for 100.22 should be same . I googled and came across some examples but they didn't match exactly what i wanted :
// just two decimal places
String.Format("{0:0.00}", 123.4567); // "123.46"
String.Format("{0:0.00}", 123.4); // "123.40"
String.Format("{0:0.00}", 123.0); // "123.00"
I don't know of anyway to put a condition in the format specifier, but you can write your own formatter:
Sorry for reactivating this question, but I didn't find the right answer here.
In formatting numbers you can use
0
as a mandatory place and#
as an optional place.So:
You can also combine
0
with#
.For this formating method is always used
CurrentCulture
. For some Cultures.
will be changed to,
.Old question but I wanted to add the simplest option in my opinion.
Without thousands separators:
With thousands separators:
The same but with String.Format:
If you need it in many places, I would use this logic in an extension method:
This worked for me!
String.Format("{0:0.00}", Convert.ToDecimal(totalPrice))
An inelegant way would be:
With
DoFormat
being something like:Not elegant but working for me in similar situations in some projects.