Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display just first 2 decimals unequal to 0

Tags:

c#

How can I display the number with just the 2 not=zero decimals?

Example:

For 0.00045578 I want 0.00045 and for 1.0000533535 I want 1.000053

like image 673
Alexis Cimpu Avatar asked Jun 29 '12 18:06

Alexis Cimpu


1 Answers

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.

like image 75
Guffa Avatar answered Nov 01 '22 10:11

Guffa