0

I want to limit the no of numbers shown in the below program. I get the result as 3.33333333333333E+15

But I want to display result variable as 3.333E+15 to match exactly as used in excel sheet.

Is there any other ways? i tried Math.Round also but its not fulfilling my requirement.

if (double.TryParse(value, out res))  //value=3333333333333333
{
    double result = Math.Truncate(res*100/100);  //result=3.33333333333333E+15
}
Deepak
  • 103
  • 1
  • 9

1 Answers1

3

For display purposes you usually tend to use format strings. In this case the format string G4 would match your desired output format. Don't mangle the values themselves to fit your format. Especially with binary floating-point that's prone to failure anyway. E.g. you could round off trailing digits only to have your number appear as 3.3330000002e15.

Note that depending on how you convert the value to a string, usage of the above-mentioned G4 differs:

var s = d.ToString("G4");
var s2 = string.Format("Value: {0:G4}", d);
Joey
  • 344,408
  • 85
  • 689
  • 683
  • is there another way to store 3.333E+15 directly in to the double result variable. I saw many tutorials but can we actually change the format of decimal while parsing it.? – Deepak Jan 22 '15 at 04:24
  • Sure, just store the value `3.333e15` in your `double` variable. However, due to the way how `double` works, it's not guaranteed that you get that exact value. Which, for the defined use cases of `double` is fine. It's for representing either very large or very small numbers with the same data type. If you need defined *decimal* precision, then you shouldn't use `double`, but `decimal`. – Joey Jan 22 '15 at 09:05