Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format decimal in C# with at least 2 decimal places

Is there a display formatter that will output decimals as these string representations in C# without doing any rounding?

The decimal may have 2 decimal places, but if it has more precision it should be included in the resultant string and not rounded off.

Examples:

decimal  -> string
20       -> 20,00
20.00    -> 20,00
20.5     -> 20,50
20.5000  -> 20,50
20.125   -> 20,125
20.12500 -> 20,125

Thanks in advance

like image 363
Fernando Meneses Gomes Avatar asked Nov 07 '14 13:11

Fernando Meneses Gomes


People also ask

What does .2f mean in C?

2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places. Similarly, had we used "%. 3f", x would have been printed rounded to 3 decimal places.

How do you write decimal numbers in C?

For example, 5.48958123 should be printed as 5.4895 if given precision is 4. In C, there is a format specifier in C. To print 4 digits after dot, we can use 0.4f in printf(). Below is program to demonstrate the same.

What does %d do in C?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.


1 Answers

When you have a reasonable upper limit for the maximum number of digits:

 ToString("0.00#######")

will handle all your examples but not 1.23456789012345M

like image 59
Henk Holterman Avatar answered Nov 12 '22 23:11

Henk Holterman