How to display only the first 2 decimal places not equal to 0

How can I display a number with two decimal places without zero?

Example:

For 0.00045578 I want 0.00045 and for 1.0000533535 I want 1.000053

+6
source share
4 answers

There is no formatting for this.

You can get the fraction of a part of the number and calculate how many zeros are there until you get two digits, and combine the format with it. Example:

double number = 1.0000533535;

double i = Math.Floor(number);
double f = number % 1.0;

int cnt = -2;
while (f < 10) {
  f *= 10;
  cnt++;
}

Console.WriteLine("{0}.{1}{2:00}", i, new String('0', cnt), f);

Conclusion:

1.000053

Note. This code only works if there is actually a fractional part of the number, and not for negative numbers. You need to add checks for this if you need to support these cases.

+3
source

. ".", , , .

, , .

+3

Try this function using parsing to find # fractional digits rather than looking for zeros (it works for negative #s as well):

private static string GetTwoFractionalDigitString(double input)
{
    // Parse exponential-notation string to find exponent (e.g. 1.2E-004)
    double absValue = Math.Abs(input);
    double fraction = (absValue - Math.Floor(absValue));
    string s1 = fraction.ToString("E1");
    // parse exponent peice (starting at 6th character)
    int exponent = int.Parse(s1.Substring(5)) + 1;

    string s = input.ToString("F" + exponent.ToString());

    return s;
}
+1
source

You can use this trick:

int d, whole;
double number = 0.00045578;
string format;
whole = (int)number;
d = 1;
format = "0.0";
while (Math.Floor(number * Math.Pow(10, d)) / Math.Pow(10, d) == whole)
{
    d++;
    format += "0";
}
format += "0";
Console.WriteLine(number.ToString(format));
0
source

All Articles