C#-截断第一个正之后的小数
一个数字是0.009012
结果应该是0.009
或者是1.1234
并且'd是1.1
或2.099
~2.09
等等
以快速和最佳的方式
从数学角度思考,使用基数为10的对数
该函数将只接受第一个密码
public double RoundOnFirstDecimal(double number)
{
int shift = -1 * ((int)Math.Floor(Math.Log10(number)));
return Math.Floor(number * Math.Pow(10, shift)) / Math.Pow(10, shift);
}
但你想这样做:(只会改变小数,而不是整数)
public double RoundOnFirstDecimal(double number)
{
int shift = -1 * ((int)Math.Floor(Math.Log10(number % 1)));
return Math.Floor(number % 1 * Math.Pow(10, shift)) / Math.Pow(10, shift) + number - number % 1;
}
这将比任何正则表达式或循环都快得多
试试这个方法:
private static string RoundSpecial(double x)
{
string s = x.ToString();
int dotPos = s.IndexOf('.');
if (dotPos != -1)
{
int notZeroPos = s.IndexOfAny(new[] { '1', '2', '3', '4', '5', '6', '7', '8', '9' }, dotPos + 1);
return notZeroPos == -1 ? s : s.Substring(0, notZeroPos + 1);
}
return s;
}
我不确定这是否是最快和最佳的方法,但它能满足你的需求。
第二种方法是使用Log10
和%
:
private static double RoundSpecial(double x)
{
int pos = -(int)Math.Log10(x - (int)x);
return Math.Round(x - (x % Math.Pow(0.1, pos + 1)), pos + 1);
}
您也可以尝试正则表达式:
decimal d = 2.0012m;
Regex pattern = new Regex(@"^(?<num>(0*[1-9]))d*$");
Match match = pattern.Match(d.ToString().Split('.')[1]);
string afterDecimal = match.Groups["num"].Value; //afterDecimal = 001
这里有一个使用数学而不是字符串逻辑的解决方案:
double nr = 0.009012;
var partAfterDecimal = nr - (int) nr;
var partBeforeDecimal = (int) nr;
int count = 1;
partAfterDecimal*=10;
int number = (int)(partAfterDecimal);
while(number == 0)
{
partAfterDecimal *= 10;
number = (int)(partAfterDecimal);
count++;
}
double dNumber = number;
while(count > 0){
dNumber /= 10.0;
count--;
}
double result = (double)partBeforeDecimal + dNumber;
result.Dump();
如果您不想使用Math
库:
static double truncateMyWay(double x)
{
double afterDecimalPoint = x - (int)x;
if (afterDecimalPoint == 0.0) return x;
else
{
int i = 0;
int count10 = 1;
do
{
afterDecimalPoint *= 10;
count10 *= 10;
i++;
} while ((int) afterDecimalPoint == 0);
return ((int)(x * count10))/((double)count10);
}
}
快乐密码!;-)