Reputation: 23
I need help trying to figure out how to round all the elements in a double array to 4 decimal places. I think I need to use either an Array.ForEach
statement or a foreach
statement, but I can't seem to get the syntax correct.
The Array has numbers (x/y coordinates) like this:
"0;24;5.99753782108473;21.770136316906;8.32805512530786;19.3909999184418"
These come from Autocad and can be up to 15 decimals long. I only need a 1/16" accuracy for what I'm trying to do so I can round it to 4 decimals without hurting anything.
Currently I am rounding the value at the time I need it with Math.Round(d1,4)
- d1 is the array name. However I think rounding the whole array at once would be "cleaner"
Upvotes: 2
Views: 4814
Reputation: 109
i think you can use foreach like this :
double array_value
foreach(Double arry in yourArray){
array_value = Math.Round(arry,4);
}
Upvotes: 0
Reputation: 726669
If you need the accuracy of 1/16-th, multiply your number by 16, round, and divide back by 16. Since 16 is a power of 2, double
will provide a precise representation of it.
To convert the whole array at once, use LINQ: first, select the new value for each item, then convert the result back to an array, like this:
d1 = d1.Select(d => Math.Round(d*16) / 16).ToArray();
You need to use System.Linq
in order for this to compile.
Upvotes: 4