Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c#
equal
double
communitycreator

How to check if two double values are equal in C#

Theodore Kelechukwu Onyejiaku

Overview

Two double objects are equal if they both have the same values. The Double.Equals() method in C# determines if two double objects are equal. It returns true if they are equal and false otherwise.

Syntax

public bool Equals (double d);
Syntax for checking if two double objects are equal

Parameters

d: This is the double object we want to compare with another double instance.

Return value

A boolean value is returned. It returns true if d is equal to the instance. Otherwise, false is returned.

Example

// use System
using System;
// create class
class DoubleEquality
{
    // main method
    static void Main()
    {
      // create double values
      double d1 = 343.13423;
      double d2 = 1.4545;
      double d3 = 5.7;
      double d4 = d3 * 1 / 1;

      // check equality
      bool b1 = d1.Equals(d2);
      bool b2 = d2.Equals(d3);
      bool b3 = d3.Equals(d4);
      bool b4 = d4.Equals(d3);

      // print results
      Console.WriteLine(b1);  // False
      Console.WriteLine(b2);  // False
      Console.WriteLine(b3);  // True
      Console.WriteLine(b4);  // True
    }
}
Check for equality of double values in C#

Explanation

  • Lines 10–13: We create some double variables, d1, d2, d3 and d4. Then we initialize them with some values.

  • Line 16: We check if d1 is equal to d2.

  • Line 17: We check if d2 is equal to d3.

  • Line 18: We check if d3 is equal to d4.

  • Line 19: We check if d4 is equal to d3.

  • Lines 22–25: We print the results to the console.

RELATED TAGS

c#
equal
double
communitycreator

CONTRIBUTOR

Theodore Kelechukwu Onyejiaku
RELATED COURSES

View all Courses

Keep Exploring