Sasha Sydoruk

Building a better mousetrap with XHTML, AJAX and RSS

Variable number of digits after the decimal point

Recently I had to format a decimal number to have at least 2 numbers after the decimal point. No big deal. Just use this format for string.Format - “{0:.00}”. But the tricky part was to show more numbers after the decimal point if available. Here is some possible combinations:

Decimal

Desired Output

Hmm… Do I need to write custom logic to handle all these cases?

No!

Here is the format you can use to achieve the desired result - “{0:.00##}”. This way everything gets formatted properly, and, as added benefit, all decimals that have more than 4 digits after the decimal point get rounded properly.

Quick and elegant!

No comments yet. Be the first.

Leave a reply