[英]C# to Lambda - count decimal places / first significant decimal
出於好奇,下面會有一個等效的Lambda表達式嗎?
...剛剛開始使用lambda,不熟悉zip等方法...
//Pass in a double and return the number of decimal places
//ie. 0.00009 should result in 5
//EDIT: Number of decimal places is good.
//However, what I really want is the position of the first non-zero digit
//after the decimal place.
int count=0;
while ((int)double_in % 10 ==0)
{
double_in*=10;
count++;
}
double1.ToString().SkipWhile(c => c!='.').Skip(1).Count()
例如:
double double1 = 1.06696;
int count = double1.ToString().SkipWhile(c => c!='.').Skip(1).Count(); // count = 5;
double double2 = 16696;
int count2 = double2.ToString().SkipWhile(c => c!='.').Skip(1).Count(); // count = 0;
Math.Ceiling(-Math.Log(double_in, 10))
我會編寫一個InfiniteSequence
函數
/// <summary>
/// Returns an inifinte sequence of integers starting with 1
/// </summary>
public static IEnumerable<int> InfiniteSequence() {
int value = 0;
while (true) {
yield return ++value;
}
}
(無論如何在.NET中都缺少這種無限枚舉:) :)然后使用它就像
var count = InfiniteSequence().Select(i => (int)(double_in * Math.Power(10,i))).TakeWhile(v=>v%10==0).Count();
這將是原始代碼的直接翻譯(除了計算10的冪的方式之外)。
如果認為這更有可能回答你的問題,並且文化不變。
Math.Max(0, num.ToString().Length - Math.Truncate(num).ToString().Length - 1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.