How to display just first 2 decimals unequal to 0

My solution would be to convert the number to a string. Search for the ".", then count zeroes till you find a non-zero digit, then take two digits.

It's not an elegant solution, but I think it will give you consistent results.


There is no built in formatting for that.

You can get the fraction part of the number and count how many zeroes there are until you get two digits, and put together the format from that. 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);

Output:

1.000053

Note: The given code only works if there actually is a fractional part of the number, and not for negative numbers. You need to add checks for that if you need to support those cases.

Tags:

C#