Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Efficient method for reducing the precision of an array of numbers using C#

Using C#, what is an efficient method to reduce the precision of an array of floating point numbers by n digits without changing type?

Example:

float[]{1.34, 2.22, 2.32, 7.71}

becomes

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

float[]{1.00, 2.00, 2.00, 8.00}

or

float[]{1.30, 2.20, 2.30, 7.70}

>Solution :

var array = new float[]{1.34f, 2.22f, 2.32f, 7.71f};

for (int i = 0; i < array.Length; i++) {
    array[i] = MathF.Round(array[i], 1); // the second argument is the number of digits after the dot
}

That will modify the existing array and the result would be float[]{1.30f, 2.20f, 2.30f, 7.70f}

If you want to create a new array:

var array = new float[]{1.34f, 2.22f, 2.32f, 7.71f};
var roundedArray = array.Select(x => MathF.Round(x, 1)).ToArray(); // or .ToList()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading