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"
something like this will work too:
If your program needs to run quickly, call value.ToString(formatString) for ~35% faster string formatting performance relative to $"{value:formatString}" and string.Format(formatString, value).
Data
Code
Code Output
References
Custom Numeric Format Strings [docs.microsoft.com]
Qt Charts BarChart Example [doc.qt.io]
To make the code more clear that Kahia wrote in (it is clear but gets tricky when you want to add more text to it)...try this simple solution.
I had to add the extra cast (decimal) to have Math.Round compare the two decimal variables.
If none of the other answers work for you, it may be because you are binding the
ContentProperty
of a control in theOnLoad
function, which means this won't work:The solution is simple: there is a
ContentStringFormat
property in the xaml. So when you create the label do this:Or
try
Here is an alternative to Uwe Keim's method, which would still maintain the same method call:
With
MyCustomFormat
being something like: