How to compare decimal values in Java

public: static int Compare(System::Decimal d1, System::Decimal d2); public static int Compare (decimal d1, decimal d2); static member Compare : decimal * decimal -> int Public Shared Function Compare (d1 As Decimal, d2 As Decimal) As Integer Int32

A signed number indicating the relative values of d1 and d2.

Return value Meaning
Less than zero d1 is less than d2.
Zero d1 and d2 are equal.
Greater than zero d1 is greater than d2.

Examples

The following example compares several Decimal values. Note that the first comparison indicates that the two values are equal despite the subtraction operation performed on the value2 variable. This is because the Decimal type has 29 digits of precision, whereas a difference between these two values can be detected only with 30 digits of precision.

using System; public enum Relationship { LessThan = -1, Equals = 0, GreaterThan = 1 } public class Example { public static void Main() { decimal value1 = Decimal.MaxValue; decimal value2 = value1 - .01m; Console.WriteLine("{0} {2} {1}", value1, value2, (Relationship) Decimal.Compare(value1, value2)); value2 = value1 / 12m - .1m; value1 = value1 / 12m; Console.WriteLine("{0} {2} {1}", value1, value2, (Relationship) Decimal.Compare(value1, value2)); value1 = value1 - .2m; value2 = value2 + .1m; Console.WriteLine("{0} {2} {1}", value1, value2, (Relationship) Decimal.Compare(value1, value2)); } } // The example displays the following output: // 79228162514264337593543950335 Equals 79228162514264337593543950335 // 6602346876188694799461995861.2 GreaterThan 6602346876188694799461995861.1 // 6602346876188694799461995861.0 LessThan 6602346876188694799461995861.2 open System type Relationship = | LessThan = -1 | Equals = 0 | GreaterThan = 1 [<EntryPoint>] let main _ = let value1 = Decimal.MaxValue let value2 = value1 - 0.01m printfn $"{value1} {Decimal.Compare(value1, value2) |> enum<Relationship>} {value2}" let value2 = value1 / 12m - 0.1m let value1 = value1 / 12m printfn $"{value1} {Decimal.Compare(value1, value2) |> enum<Relationship>} {value2}" let value1 = value1 - 0.2m let value2 = value2 + 0.1m printfn $"{value1} {Decimal.Compare(value1, value2) |> enum<Relationship>} {value2}" 0 // The example displays the following output: // 79228162514264337593543950335 Equals 79228162514264337593543950335 // 6602346876188694799461995861.2 GreaterThan 6602346876188694799461995861.1 // 6602346876188694799461995861.0 LessThan 6602346876188694799461995861.2 Public Enum Relationship As Integer LessThan = -1 Equals = 0 GreaterThan = 1 End Enum Module Example Public Sub Main() Dim value1 As Decimal = Decimal.MaxValue Dim value2 As Decimal = value1 - .01d Console.WriteLine("{0} {2} {1}", value1, value2, CType(Decimal.Compare(value1, value2), Relationship)) value2 = value1 / 12d - .1d value1 = value1 / 12d Console.WriteLine("{0} {2} {1}", value1, value2, CType(Decimal.Compare(value1, value2), Relationship)) value1 = value1 - .2d value2 = value2 + .1d Console.WriteLine("{0} {2} {1}", value1, value2, CType(Decimal.Compare(value1, value2), Relationship)) End Sub End Module ' The example displays the following output: ' 79228162514264337593543950335 Equals 79228162514264337593543950335 ' 6602346876188694799461995861.2 GreaterThan 6602346876188694799461995861.1 ' 6602346876188694799461995861.0 LessThan 6602346876188694799461995861.2

Applies to

  • CompareTo(Object)
  • Equals(Object)

Significant digits are referred to all digits inclusive of left and right to decimal place keeping a note adding 0 to left of any number is not countable as significant digits whereas precise digits referred to digits that are only lying on the right side or in short after the decimal place in mathematics. In Java, there are numbers more than 16 numbers only to the precision but can go more. Here we are given a double value, the task is to set its precision value to specific decimal places. It is illustrated below illustrations as follows:

Illustrations: 

Input : val = 1 Output : 1.0000 Upto 4 decimal placesInput : 12.5 Output : 12.500000 Upto 6 decimal places
  1. Using format() Method of String class
  2. Using round() method of Math class

We can use format() method of String class to format the decimal number to some specific format.

Syntax:

String.format("%.Df", decimalValue); // Where D is the number required number of Decimal places

Example-1:

  public static void main(String[] args) {

      String.format("%.20f", a));

      String.format("%.5f", b));

Output 0.90000000000000000000 1.00000

From the above output, it is clear that precision of 20 digits is been carried out for the first entry whereas precision to 5 digits is carried out on input double value. 

Example-2:

    public static void main (String[] args) {

      Formatter fm=new Formatter();

      fm.format("%.4f", 123.1234567);

      fm.format("%16.2e",123.1234567);

      System.out.println("GFG!");

      fm.format("%.15s", "Learning with Gfg is easy quick");

Output 123.1235 GFG! Learning with G

Example:

    public static void main(String[] args)

        double num = 3.141414141414;

            = Math.round(num * 10000000) / 10000000.0;

The above double number is precise to 7 digits which can easily be seen from the output generated. 


Article Tags :

In this article, we will see what is the problem in comparing floating-point numbers and we will discuss the correct way to compare two floating-point numbers. 
What is the problem in comparing Floating-Point Numbers usually?
Let us first compare two floating-point numbers with the help of relational operator (==).
Example: Using “==” for comparison
 

void compareFloatNum(double a, double b)

        cout << "The numbers are equal"

        cout << "The numbers are not equal"

    double a = (0.3 * 3) + 0.1;

    static void compareFloatNum(double a, double b)

            System.out.print("The numbers are equal" + "\n");

            System.out.print("The numbers are not equal" + "\n");

    public static void main(String[] args)

        double a = (0.3 * 3) + 0.1;

def compareFloatNum(a, b):

        print("The numbers are equal")

        print("The numbers are not equal")

    static void comparefloatNum(double a, double b)

            Console.Write("The numbers are equal" + "\n");

            Console.Write("The numbers are not equal" + "\n");

    public static void Main(String[] args)

        double a = (0.3 * 3) + 0.1;

function compareFloatNum(a,b)

            document.write("The numbers are equal" + "<br>");

            document.write("The numbers are not equal" + "<br>");

Output:  The numbers are not equal

Why does this problem occur?
In the case of floating-point numbers, the relational operator (==) does not produce correct output, this is due to the internal precision errors in rounding up floating-point numbers.In the above example, we can see the inaccuracy in comparing two floating-point numbers using “==” operator. The two numbers ‘a’ and ‘b’ are equal ( as (0.3 * 3) + 0.1 = 1 ) but the program results in an incorrect output.Let’s take a closer look at the numbers in the next snippet.

void printFloatNum(double a, double b)

    cout << setprecision(20);

    cout << "a is : " << a << endl;

    cout << "b is : " << b << endl;

    double a = (0.3 * 3) + 0.1;

if __name__ == "__main__":

Output:  a is : 0.99999999999999988898 b is : 1

Now we can see the internal rounding error in floating-point numbers. Number ‘a’ is not correctly rounded up to 1, there is an internal error in rounding up, a very small error but makes a huge difference when we are comparing the numbers.

How to compare floating-point numbers correctly? 

If we do have to compare two floating-point numbers then rather than using “==” operator we will find the absolute difference between the numbers (which if were correctly represented, the difference would have been 0) and compare it with a very small number 1e-9 (i.e 10^-9, this number is very small) and if the difference is less than this number, we can safely say that the two floating-point numbers are equal.

Example: 


 

void compareFloatNum(double a, double b)

        cout << "The numbers are equal "

        cout << "The numbers are not equal "

    double a = (0.3 * 3) + 0.1;

static void compareFloatNum(double a, double b)

    if (Math.abs(a - b) < 1e-9)

        System.out.print("The numbers are equal "

        System.out.print("The numbers are not equal "

public static void main(String[] args)

    double a = (0.3 * 3) + 0.1;

def compareFloatNum(a, b):

        print("The numbers are equal ");

        print("The numbers are not equal ");

if __name__ == '__main__':

static void comparefloatNum(double a, double b)

    if (Math.Abs(a - b) < 1e-9)

        Console.Write("The numbers are equal "

        Console.Write("The numbers are not equal "

public static void Main(String[] args)

    double a = (0.3 * 3) + 0.1;

function compareFloatNum(a,b)

    if (Math.abs(a - b) < 1e-9)

        document.write("The numbers are equal "

        document.write("The numbers are not equal "

Output:  The numbers are equal

This code results in the correct output, so whenever two floating point numbers are two be compared then rather than using “==” operator, we will use the above technique.
 


Article Tags :