L
L
LuckyGuys2018-02-01 12:46:36
C++ / C#
LuckyGuys, 2018-02-01 12:46:36

What's the easiest way to round three numbers in a row without using iteration in C#?

Now it looks like this:

double a, b, c;
Console.WriteLine(Math.Round(a, 2)+" "+ Math.Round(b, 2)+" "+Math.Round(c, 2));

Is it possible to apply Math.Round or {0:F2} formatting to an array of numbers without a loop? Or maybe there is another solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Pavlov, 2018-02-01
@lexxpavlov

Without a loop, just as you said (with options in the form of creating temporary variables with the results). Otherwise you need a cycle. But the cycle can be inside some function, for example, in string.Join. And then, you still have to manually place the data in the array.

double a = 10.123, b = 20.234, c = 30.345;
Console.WriteLine(Math.Round(a, 2) + " " + Math.Round(b, 2) + " " + Math.Round(c, 2));
Console.WriteLine(string.Join(" ", new []{a, b, c}.Select(x => x.ToString("F2"))));

You can also try to go crazy - put data in fields and get a list of fields through reflection.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question