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

Time:12-13

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

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

or

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

CodePudding user response:

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()
  • Related