1
Guys, someone knows a way that I can transform a number with at least 5 significant digits and added to this factor, it should have at least 2 decimal places.
Example:
-0,00012 >> -0,00012000
12345687,00 >> 12345687,00
123,00 >> 123,00
123,21254 >> 123,21
NOTE: Significant digit starts from the first non-zero number, from left to right
I arrived in this function, but surely to improve, I did running!
static string RoundToSignificantDigits(decimal d)
{
string numero = d.ToString();
if (numero.IndexOf(",") == -1) numero += ",00";
int signif = 0;
int index = 0;
bool startCount = false;
for (int i = 0; i < numero.Length; i++)
{
index = i;
if (!startCount && numero[i] != '0' && numero[i] != ',' && numero[i] != '-')
{
startCount = true;
}
if (numero[0] == '0' && i == 0)
{
i = 2;
}
if (numero[i] != ',' && numero[i] != '-')
{
if (startCount)
signif++;
}
if (signif == 5)
break;
}
int alg = d < 0 ? 1 : 0;
if ((d>0.001m &&index == 4) || (index > numero.IndexOf(",") && numero[alg] != '0'))
{
string[] parts0 = numero.Split(',');
parts0[1] = parts0[1].Substring(0, 2);
numero = string.Join(",", parts0);
if (index<parts0[0].Length || signif ==5)
{
return numero;
}
}
else if (numero[alg] == '0')
{
numero = numero.Substring(0, index + 1);
}
else
{
string[] parts = numero.Split(',');
parts[1] = parts[1].PadRight(2, '0');
numero = string.Join(",", parts);
return numero;
}
if (numero.IndexOf("-") != -1)
{
if (d < 0)
{
string[] parts = numero.Split(',');
int numbers = parts[1].TrimStart('0').Length;
int pad0 = 5 - numbers;
if (pad0 > 0)
{
parts[1] = parts[1].PadRight(parts[1].Length + pad0, '0');
}
numero = string.Join(",", parts);
}
else
{
numero = numero.PadRight(7, '0');
}
}
else
{
string[] parts = numero.Split(',');
int numbers = parts[1].TrimStart('0').Length;
int pad0 = 5 - numbers;
if (pad0 > 0 && pad0 != 5)
{
parts[1] = parts[1].PadRight(parts[1].Length + pad0, '0');
}
numero = string.Join(",", parts);
}
return numero;
}
For me it was not very clear the first example. Why was added three zeros on the right?
– Woss
Significant digit starts counting from the first non-zero number, left to right
– Bruno Henri
Do a for in the string by checking the non-zero, comma and number of characters position.
– Denis