Math.Round issue in C#

Dilini Wijekoon 20 Reputation points
2023-12-06T04:59:19.0166667+00:00

Below is my program with some sample values;

using System; 

class Geeks 
{ 

	public static void Main() 
	{ 
	
		double[] val = {18527.475,28527.475,38527.475}; 
		

		Console.WriteLine("Rounded values are:"); 
		
		foreach(double value in val) 
		
		
			Console.WriteLine("{0} == {1}", value, Math.Round(value, 2, 
											MidpointRounding.AwayFromZero)); 
			
	} 
}

I got the results below

Rounded values are:

18527.475 == 18527.47

28527.475 == 28527.48

38527.475 == 38527.48.

My question is why 18527.475 is rounding as .47 while others are rounding as .48?

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,631 questions
{count} votes

Accepted answer
  1. KOZ6.0 6,300 Reputation points
    2023-12-06T11:55:41.8566667+00:00

    Since the double type stores binary numbers, it may not be possible to accurately hold values below the decimal point. Let's add each value 1000 times.

    double[] val = { 18527.475, 28527.475, 38527.475 };
    foreach (double value in val) {
        double sumValue = 0;
        for (int i = 0; i < 1000; i++) {
            sumValue += value;
        }
        Console.WriteLine(sumValue);
    }
    
    18527474.999999903
    28527475.00000046
    38527475.00000072
    

    Use decimal type.

    decimal[] val = { 18527.475m, 28527.475m, 38527.475m };
    Console.WriteLine("Rounded values are:");
    foreach (decimal value in val)
        Console.WriteLine("{0} == {1}", value, Math.Round(value, 2,
                                        MidpointRounding.AwayFromZero));
    
    
    Rounded values are:
    18527.475 == 18527.48
    28527.475 == 28527.48
    38527.475 == 38527.48
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 61,416 Reputation points
    2023-12-06T16:20:39.4+00:00

    A Double is stored in base 2. Decimal numbers can not accurately stored in base 2. Much like 1/3 can not be converted to decimal, several decimal values can not be converted to base 2.

    1 person found this answer helpful.
    0 comments No comments