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"
This is a common formatting floating number use case.
Unfortunately, all of the built-in one-letter format strings (eg. F, G, N) won't achieve this directly.
For example,
num.ToString("F2")
will always show 2 decimal places like123.40
.You'll have to use
0.##
pattern even it looks a little verbose.A complete code example:
I am afraid there is no built-in format that will do this. You will have to use a different format depending on whether the value is a whole number or not. Or always format to 2 decimal places, and manipulate the string afterwards to remove any trailing ".00".
Simple one line code :