In C# I have an array of double (double[]
I mean)
I want to round all values to two decimal places in C#.
One solution is to do this with foreach()
and Math.Round()
functions
but the array is very large (1.000.000 to 10.000.000 values)
Instead of foreach
, is there a more efficient solution?
Instead of foreach, a more efficient solution?
Nope. Fundamentally, if you want to round all the values, you've got to round all the values. There's no magic that will make that simpler.
Of course, if you're only going to access a few of the values, you could potentially redesign your code to lazily round on access - or even on display - but if you really need the rounded versions of all the values, there's nothing that will make that faster than an O(n) operation.
You could do it in parallel as noted in other answers, which may well make it faster - but it will simultaneously be less efficient than a single-threaded approach. (You'll end up doing more work, because of the coordination involved - but you'll still get it done faster overall, probably.)
You haven't said anything about why you want to round these values though - usually, you should only round values at the point of display. Are you really sure you need to round them before then? What do the values represent? (If they're financial values, you should strongly consider decimal
instead of double
.)
See more on this question at Stackoverflow