Format a decimal number with a given maximum precision, but without unnecessary trailing zeros

I used the following code to format decimals

return string.Format(CultureInfo.CreateSpecificCulture("nb-NO"), "{0:N3}", decVal);

If decVal does not contain decimal places, I do not want to show decimal points, but I want to show a figure with the correct formatting without s zero. How to do it?

+4
source share
1 answer

You can use your own digital format, for example:

return string.Format(CultureInfo.CreateSpecificCulture("nb-NO"), "{0:0.###}", decVal);

You can read about standard number formats and custom number formats.

EDIT:

To handle thousands separators, you can use:

return string.Format(CultureInfo.CreateSpecificCulture("nb-NO"), "{0:#,0.###}", decVal);

, SO-.

P.S.: @Luaan (0. ###);

+9

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


All Articles