-2

I want to show maximum 2 decimal of a double variable in string format. How to write a function to show the non-zero decimal?

Example:

double intVar = 1;
double oneDice = 1.1;
double twoDice = 1.11;
double threeDice = 1.111;

Console.writeLine(yourFunction(intVar)); //output  1
Console.writeLine(yourFunction(oneDice)); //output  1.1
Console.writeLine(yourFunction(twoDice)); //output  1.11
Console.writeLine(yourFunction(threeDice)); //output  1.11
thepirat000
  • 12,362
  • 4
  • 46
  • 72
king yau
  • 500
  • 1
  • 9
  • 28
  • 2
    From http://stackoverflow.com/a/2453982/6741868, you can first do `double x = Math.Truncate(threeDice * 100) / 100;` then `string s = string.Format("{0:N2}%", x);`. For all 3 of them. – Keyur PATEL Sep 27 '16 at 03:31
  • @KeyurPATEL by using yours, i got 2.29 when enter 2.3.... Why? – king yau Sep 27 '16 at 03:47
  • I see the problem. I will shift my comment to an answer since it requires a few lines of code. – Keyur PATEL Sep 27 '16 at 03:56
  • See also https://stackoverflow.com/questions/164926/c-sharp-how-do-i-round-a-decimal-value-to-2-decimal-places-for-output-on-a-pa (formatting codes for `decimal` are the same as for `double`), https://stackoverflow.com/questions/2453951/c-sharp-double-tostring-formatting-with-two-decimal-places-but-no-rounding (in case you want truncation instead of rounding), or any of the other literally thousands of questions on Stack Overflow involving how to format `double` values. – Peter Duniho Sep 27 '16 at 07:08

1 Answers1

0

From the link in my comment, https://stackoverflow.com/a/2453982/6741868, and a little other code:

public string yourFunction(double val)
{
    double x = val;

    if (BitConverter.GetBytes(decimal.GetBits((decimal)val)[3])[2] > 2)   //check if there are more than 2 decimal places
    {
        x = Math.Truncate(val * 100) / 100;           
        string s = string.Format("{0:N2}", x);
        return s;
    }
    return x.ToString();
}

If there are more than 2 decimal places, it will truncate the rest (NOT round) and convert to a string with 2 decimal places showing.

Otherwise it simply returns the original value, converted to string.

Feel free to modify the function according to your further needs, or if you want to tweak the output string a little more.

Edit

Personally tested values:

1, 1.1, 1.11, 1.111, 1.138234732

Results:

1, 1.1, 1.11, 1.11, 1.13

Community
  • 1
  • 1
Keyur PATEL
  • 2,299
  • 1
  • 15
  • 41