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?
We can use DecimalFormat("0.00") to ensure the number always round to 2 decimal places.
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.
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.
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With