We help IT Professionals succeed at work.
Get Started

Format a number with comma separators and variable decimal places.

Last Modified: 2015-03-09
When I first ran into this problem, I though I was crazy and that I was just missing the obvious answer. But after an hour of Google searching I'm out of ideas.
I'm trying to format a number that the user types in so that it has commas in the right places (at the thousands, millions, etc), but also allow for decimals IF THERE ARE ANY.

So far I've found Decimal.ToString("N"). which works fine for the thousands separator but only allows for a fixed number of decimal points. I need to be able to have no decimal points if the number is an integer, and any number of decimal points is the number is a decimal.

Here are some examples of user input and how I want them to come out:

12 -> 12
12.5 -> 12.5
1000 -> 1,000
1000.5 -> 1,000.5
1000.567 -> 1,000.567
123123123.45678 -> 123,123,123.45678

Is there any way to get the desired format?
Watch Question
Distinguished Expert 2019
This problem has been solved!
Unlock 1 Answer and 5 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE