C# : Math functions
i'm having a List<Double>
List<Double>lst=new List<Double>{ 1.0,2.409,3.0}
I need to convert this开发者_开发知识库 list into a List<String>
So the result should contain
{ "1","2.409","3"}
in the result if the value does not have any floating points then need not add .0
Please help me to do this
If you're using .Net 3.5 you can use Linq:
lst.Select(n => String.Format("{0:0.###}", n));
Otherwise, you can do this the long way:
var output = new List<string>();
foreach (int number in lst)
{
output.Add(String.Format("{0:0.###}", number));
}
Here is my take on this that doesn't rely on culture specific fraction separator, nor fixed amount of decimal places:
var result = lst.Select(
n => {
double truncated = Math.Truncate(n);
if(truncated == n) {
return truncated.ToString("0");
} else {
return n.ToString();
}
}
);
List<Double> lst=new List<Double>() { 1.0,2.409,3.0};
List<string> output = lst.Select(val => val.ToString("0.######")).ToList();
should do what you want
List lst = new List { 1.0, 2.409, 3.0 };
List newlist = lst.Select(val => val.ToString()).ToList();
Less writing....
精彩评论