Possible Duplicate:
Engineering notation in C#?
Whether a metric prefix is preferable to the scientific notation may be up for debate but i think it has its use-cases for physical units.
I had a look around but it seems .NET does not have anything like that built in, or am i mistaken about that? Any method of achieving that would be fine.
As a clarification: The goal is to display any given number as a floating point or integer string with a value between 1 and 999 and the respective metric prefix.
e.g.
1000 -> 1k
0.05 -> 50m
With some rounding:
1,436,963 -> 1.44M
Metric notation uses a prefix for exponents corresponding to the traditional name or number of commas. Scientific notation uses the power of 10 to show the magnitude of a number.
Try this out. I haven't tested it, but it should be more or less correct.
public string ToSI(double d, string format = null)
{
char[] incPrefixes = new[] { 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y' };
char[] decPrefixes = new[] { 'm', '\u03bc', 'n', 'p', 'f', 'a', 'z', 'y' };
int degree = (int)Math.Floor(Math.Log10(Math.Abs(d)) / 3);
double scaled = d * Math.Pow(1000, -degree);
char? prefix = null;
switch (Math.Sign(degree))
{
case 1: prefix = incPrefixes[degree - 1]; break;
case -1: prefix = decPrefixes[-degree - 1]; break;
}
return scaled.ToString(format) + prefix;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With