I want to shorten a number to the first significant digit that is not 0. The digits behind should be rounded.
Examples:
0.001 -> 0.001
0.00367 -&g
I would declare precision variable and use a iteration multiplies that variable by 10 with the original value it didn't hit, that precision will add 1.
then use precision variable be Math.Round second parameter.
static decimal RoundFirstSignificantDigit(decimal input) {
int precision = 0;
var val = input;
while (Math.Abs(val) < 1)
{
val *= 10;
precision++;
}
return Math.Round(input, precision);
}
I would write an extension method for this function.
public static class FloatExtension
{
public static decimal RoundFirstSignificantDigit(this decimal input)
{
int precision = 0;
var val = input;
while (Math.Abs(val) < 1)
{
val *= 10;
precision++;
}
return Math.Round(input, precision);
}
}
then use like
decimal input = 0.00001;
input.RoundFirstSignificantDigit();
c# online
Result
(-0.001m).RoundFirstSignificantDigit() -0.001
(-0.00367m).RoundFirstSignificantDigit() -0.004
(0.000000564m).RoundFirstSignificantDigit() 0.0000006
(0.00000432907543029m).RoundFirstSignificantDigit() 0.000004