Languages
[Edit]
EN

C# / .NET - round List elements to two decimal places

0 points
Created by:
martineau
1380

In this article, we would like to show you how to round List elements to two decimal places in C#.

Quick solution:

List<double> myList = new List<double> { 1.234, 1.2345, 1.23456 };

myList = myList.Select(x => Math.Round(x, 2)).ToList();

 

Practical example

In this example, we use Math.Round() to round numbers to two decimal places.

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        List<double> myList = new List<double> { 1, 1.2, 1.23, 1.234, 1.2345 };

        myList = myList.Select(x => Math.Round(x, 2)).ToList();

        // display result
        myList.ForEach(x => Console.WriteLine(x));
    }
}

Output:

1
1.2
1.23
1.23
1.23

References

  1. Enumerable.Select Method (System.Linq) | Microsoft Docs
  2. Math.Round Method (System) | Microsoft Docs
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join