C
C#2mo ago
DragonA.

Math.Round issue

I have strange issue with Math.Round in a first example I use it to round a double after calculation, and the output wrong, because it has to have 2 digits after dot, but the output have more digits after dot. string input = Console.ReadLine(); double r = double.Parse(input); const double pi = 3.14; double volume = 4 * pi * r * r * r / 3; Math.Round(volume, 2); Console.WriteLine($"volume: {volume}"); r = 2 volume: 33,49333333333333 In a second example I round first of all round the result and then give it to the variable and all working right. string input = Console.ReadLine(); double r = double.Parse(input); const double pi = 3.14; double volume = Math.Round(4 * pi * r * r * r / 3, 2); Console.WriteLine($"volume: {volume}"); r = 2 volume: 33,49 Why is it happen like that?
1 Reply
Pobiega
Pobiega2mo ago
Short answer: Because of how floating point numbers work And in your first example, you dont save the result of the rounding Math.Round returns the result, and you are not capturing the return value how floating point numbers (such as float and double) work behind the scenes is actually quite interesting and very important to understand. A side effect of how they work is that they cant accurately represent all numbers, and rounding to a certain number of digits etc is mostly a display concern and should be done when displaying the number (as a string, not as a double)
Want results from more Discord servers?
Add your server