将十进制数字四舍五入到不为零的第一个十进制位置 [英] Round a decimal number to the first decimal position that is not zero
问题描述
我想将数字缩短为不为0的第一个有效数字。后面的数字应四舍五入。
I want to shorten a number to the first significant digit that is not 0. The digits behind should be rounded.
示例:
0.001 -> 0.001
0.00367 -> 0.004
0.00337 -> 0.003
0.000000564 -> 0.0000006
0.00000432907543029 -> 0.000004
当前,我有以下步骤:
if (value < (decimal) 0.01)
{
value = Math.Round(value, 4);
}
注意:
- 数字将始终为正
- 有效数字的数量将始终为1
- 值较大的0.01将始终为四舍五入到两位小数,因此if< 0.01
从上面的示例中可以看到,四舍五入到小数点后四位可能不够,并且值可能会有很大差异。
As you can see from the examples above, a rounding to 4 Decimal places might not be enough and the value might vary greatly.
推荐答案
我将声明 precision
变量,并使用迭代将该变量乘以加上 10
并没有达到原始值,则精度
将增加 1
。
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
.
然后使用 precision
变量为 Math.Round
第二个参数。
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);
}
}
然后使用
decimal input = 0.00001;
input.RoundFirstSignificantDigit();
结果
(-0.001m).RoundFirstSignificantDigit() -0.001
(-0.00367m).RoundFirstSignificantDigit() -0.004
(0.000000564m).RoundFirstSignificantDigit() 0.0000006
(0.00000432907543029m).RoundFirstSignificantDigit() 0.000004
这篇关于将十进制数字四舍五入到不为零的第一个十进制位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!