Madhu
Madhu

Reputation: 41

Exponents in C#

int trail = 14;
double mean = 14.00000587000000;
double sd = 4.47307944700000;

double zscore = double.MinValue;

zscore = (trail - mean) / sd; //zscore at this point is exponent value -1.3122950464645662E-06

zscore = Math.Round(zscore, 14); //-1.31229505E-06

Math.Round() also keeps the exponent value. should zscore.ToString("F14") be used instead of Math.Round() function to convert it to non-exponent value? Please explain.

Upvotes: 3

Views: 1039

Answers (1)

Pac0
Pac0

Reputation: 23129

These are completely independant concerns.

Math.Round will actually return a new value, rounded to the specified decimal (ar at least, as near as one can do with floating point).

You can reuse this result value anywhere, and show it with 16 decimals precision if you want, but it's not supposed to be the same as the original one.

The fact that it is displayed with exponent notation or not has nothing to do with Round.


When you use ToString("F14") on a number, this is a display specification only, and does not modify the underlying value in any way. The underlying value might be a number that would or would not display as exponential notation otherwise, and may or may actually have 14 significant digits.

It simply forces the number to be displayed as a full decimal without exponent notation, with the number of digits specified. So it seems to be what you actually want.


Examples :

(executable online here : http://rextester.com/PZXDES55622)

double num = 0.00000123456789;

Console.WriteLine("original :");
Console.WriteLine(num.ToString());
Console.WriteLine(num.ToString("F6"));
Console.WriteLine(num.ToString("F10"));
Console.WriteLine(num.ToString("F14"));

Console.WriteLine("rounded to 6");
double rounded6 = Math.Round(num, 6);
Console.WriteLine(rounded6.ToString());
Console.WriteLine(rounded6.ToString("F6"));
Console.WriteLine(rounded6.ToString("F10"));
Console.WriteLine(rounded6.ToString("F14"));

Console.WriteLine("rounded to 10");
double rounded10 = Math.Round(num, 10);
Console.WriteLine(rounded10.ToString());
Console.WriteLine(rounded10.ToString("F6"));
Console.WriteLine(rounded10.ToString("F10"));
Console.WriteLine(rounded10.ToString("F14"));

will output:

original :
1,23456789E-06
0,000001
0,0000012346
0,00000123456789
rounded to 6
1E-06
0,000001
0,0000010000
0,00000100000000
rounded to 10
1,2346E-06
0,000001
0,0000012346
0,00000123460000

Upvotes: 7

Related Questions