Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# how to String.Format decimal with unlimited decimal places?

Tags:

c#

I need to convert a decimal number to formatted string with thousand groups and unlimited (variable) decimal numbers:

1234 -> "1,234"
1234.567 -> "1,234.567"
1234.1234567890123456789 -> "1,234.1234567890123456789"

I tried String.Format("{0:#,#.#}", decimal), but it trims any number to max 1 decimal place.

like image 316
jurev Avatar asked Oct 17 '11 14:10

jurev


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


2 Answers

You can use # multiple times (see Custom Numeric Format Strings):

string.Format("{0:#,#.#############################}", decimalValue)

Or, if you're just formatting a number directly, you can also just use decimal.ToString with the format string.

However, there is no way to include "unlimited decimal numbers". Without a library supporting arbitrary precision floating point numbers (for example, using something like BigFloat from Extreme Numerics), you'll run into precision issues eventually. Even the decimal type has a limit to its precision (28-29 significant digits). Beyond that, you'll run into other issues.

like image 51
Reed Copsey Avatar answered Oct 18 '22 19:10

Reed Copsey


As I've said, the decimal type has a precision of 28-29 digits.

decimal mon = 1234.12345678901234567890123M;
var monStr = mon.ToString("#,0.##############################");
var monStr2 = String.Format("{0:#,0.##############################}", mon);

Here there are 30x# after the decimal separator :-)

I've changed one # with 0 so that 0.15 isn't written as .15 .

like image 43
xanatos Avatar answered Oct 18 '22 17:10

xanatos