我想把一个数字缩短到第一个重要数字,而不是0。后面的数字应该四舍五入。
示例:
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);
}
注意:
正如您可以从上面的例子中看到的,四舍五入到4个十进制位置可能是不够的,而且值可能有很大的差异。
发布于 2018-09-21 09:58:46
我将声明precision
变量,并使用迭代将该变量乘以10
与它未命中的原始值相乘,precision
将添加1
。
然后使用precision
变量是Math.Round
第二个参数。
我对这个方法增加了一些修改,它不仅可以支持零小数点,还可以支持所有十进制数。
static decimal RoundFirstSignificantDigit(decimal input) {
if(input == 0)
return input;
int precision = 0;
var val = input - Math.Round(input,0);
while (Math.Abs(val) < 1)
{
val *= 10;
precision++;
}
return Math.Round(input, precision);
}
我会为这个函数编写一个扩展方法。
public static class FloatExtension
{
public static decimal RoundFirstSignificantDigit(this decimal input)
{
if(input == 0)
return input;
int precision = 0;
var val = input - Math.Round(input,0);
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
发布于 2018-09-21 10:01:18
像那样吗?
public decimal SpecialRound(decimal value)
{
int posDot = value.ToString().IndexOf('.'); // Maybe use something about cultural (in Fr it's ",")
if(posDot == -1)
return value;
int posFirstNumber = value.ToString().IndexOfAny(new char[9] {'1', '2', '3', '4', '5', '6', '7', '8', '9'}, posDot);
return Math.Round(value, posFirstNumber);
}
发布于 2018-09-21 10:04:40
var value = 0.000000564;
int cnt = 0;
bool hitNum = false;
var tempVal = value;
while (!hitNum)
{
if(tempVal > 1)
{
hitNum = true;
}
else
{
tempVal *= 10;
cnt++;
}
}
var newValue = (decimal)Math.Round(value, cnt);
https://stackoverflow.com/questions/52440913
复制相似问题