Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format double type with minimum number of decimal digits

Tags:

c#

.net

I need to format double type so that it has minimum two decimal digits but without limitation for maximum number of decimal digits:

5     -> "5.00"
5.5   -> "5.50"
5.55  -> "5.55"
5.555 -> "5.555"
5.5555 -> "5.5555"

How can I achieve it?

like image 305
SiberianGuy Avatar asked Sep 15 '11 15:09

SiberianGuy


People also ask

How do you limit a double to two decimal places?

We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.

How many decimal digits double data type can hold?

double is a 64-bit IEEE 754 double precision Floating Point Number – 1 bit for the sign, 11 bits for the exponent, and 52* bits for the value. double has 15 decimal digits of precision.

How do I print 2 digits after a decimal?

we now see that the format specifier "%. 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.


2 Answers

You can use the 0 format specificer for non-optional digits, and # for optional digits:

n.ToString("0.00###")

This example gives you up to five decimal digits, you can add more # positions as needed.

like image 124
Guffa Avatar answered Oct 16 '22 12:10

Guffa


Try this

    static void Main(string[] args)
    {
        Console.WriteLine(FormatDecimal(1.678M));
        Console.WriteLine(FormatDecimal(1.6M));
        Console.ReadLine();

    }

    private static string FormatDecimal(decimal input)
    {
        return Math.Abs(input - decimal.Parse(string.Format("{0:0.00}", input))) > 0 ?
            input.ToString() :
            string.Format("{0:0.00}", input);
    }
like image 40
Sandeep G B Avatar answered Oct 16 '22 14:10

Sandeep G B