I'm trying to format some large numbers in scientific format, but I need the power in multiples of three. Is there a recommended way to do this?
I have a range of numbers in a table and instead of true scientific format (with a single digit before the decimal point) I'm happy to have that change in order to have a power with a multiple of three, for example:
3.123e+003
19.523e+003
Rather than:
3.123e+003
1.952e+004
Having all the powers as multiples of three makes my table easier to scan, I believe.
Thanks in advance
I think you need to write your own function. At first you can get the scientific representation of the number with the precision two digits larger than you need. Then you should parse resulting string to get floating-point coefficient and 10's power index as numbers of type decimal. After that you analyse the remainder of division index by 3 and change the numbers in the appropriate way. Finally you generate output string.
static string Scientific3(double value, int precision)
{
string fstr1 = "{0:E" + (precision+2).ToString() + "}";
string step1 = string.Format(fstr1, value);
int index1 = step1.ToLower().IndexOf('e');
if (index1 < 0 || index1 == step1.Length - 1)
throw new Exception();
decimal coeff = Convert.ToDecimal(step1.Substring(0, index1));
int index = Convert.ToInt32(step1.Substring(index1 + 1));
while(index%3!=0)
{
index--;
coeff *= 10;
}
string fstr2 = "{0:F" + precision.ToString() + "}E{1}{2:D3}";
return string.Format(fstr2, coeff, ((index < 0) ? "-" : "+"), Math.Abs(index));
}
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