C #: math functions

I have a List<Double>

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

I need to convert this list to List<String>

Thus, the result should contain

  { "1","2.409","3"} 

as a result, if the value has no floating points, then you do not need to add .0

Please help me do this

+4
source share
4 answers

If you are using .Net 3.5, you can use Linq:

 lst.Select(n => String.Format("{0:0.###}", n)); 

Otherwise, you can do it a long way:

 var output = new List<string>(); foreach (int number in lst) { output.Add(String.Format("{0:0.###}", number)); } 
+4
source

Here is my approach to this, which is independent of the culture-specific fraction separator, or a fixed number of decimal places:

 var result = lst.Select( n => { double truncated = Math.Truncate(n); if(truncated == n) { return truncated.ToString("0"); } else { return n.ToString(); } } ); 
+1
source
  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

0
source
 List lst = new List { 1.0, 2.409, 3.0 }; List newlist = lst.Select(val => val.ToString()).ToList(); 

Write less ....

0
source

Source: https://habr.com/ru/post/1333879/


All Articles