简体   繁体   English

C#:数学函数

[英]C# : Math functions

i'm having a List<Double> 我有一个List<Double>

  List<Double>lst=new List<Double>{ 1.0,2.409,3.0}

I need to convert this list into a List<String> 我需要将此列表转换为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 在结果中,如果值没有任何浮点,则不需要添加.0

Please help me to do this 请帮我这样做

If you're using .Net 3.5 you can use Linq: 如果你使用.Net 3.5,你可以使用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.... 少写......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM