Skip to content

Instantly share code, notes, and snippets.

@0ryant
Created August 1, 2019 11:28
Show Gist options
  • Save 0ryant/79f0347dc6d1ec9c364749d448e09f90 to your computer and use it in GitHub Desktop.
Save 0ryant/79f0347dc6d1ec9c364749d448e09f90 to your computer and use it in GitHub Desktop.
Java - Coding Challenge 5 - Decimal Comparator
// numbers must be equal up to 3 decimal places
public class DecimalComparator {
public static boolean areEqualByThreeDecimalPlaces(double first,double second) {
if (first <0 && second >0 || first >0 && second <0){
return false;
}
double firstThousand = first*1000;
double secondThousand = second*1000;
int firstint = (int)firstThousand;
int secondint = (int)secondThousand;
if (firstint==secondint){
return true;
}
return false;
}
}
@migosJava73
Copy link

why is the double being multiple to 1000?

@nicofr9
Copy link

nicofr9 commented Mar 23, 2022

for be comparable, instead of compare those decimal numbers you compare 2 int numbers, if you look line 14 he use casting

@ilialloyd
Copy link

 public static boolean areEqualByThreeDecimalPlaces(double first, double second) {

 if (first <0 && second >0 || first >0 && second <0){
                return false;
            }


// you can cast directly without using second pair or double
        int i = (int)(first*1000);  
            int j = (int)(second*1000);

            if(i==j){
                return true;
            }
            return false;
   }

@erictshibangu02
Copy link

erictshibangu02 commented Oct 13, 2022

Can some body explainme about this

package edu.fcc.cmis.decimalcomparator;

public class DecimalComparator {

// Write your 3 methods here






// Use the main method to test your code (optional)
public static void main(String[] args) {

// System.out.println(sameIntegralPart(22.34, 22.37867)); // true
// System.out.println(sameIntegralPart(141457105122.34667, 141457105111.34667)); // false
//
// System.out.println(areEqualWithinPrecision(-1341.235, -1341.23534667, 3)); // true
// System.out.println(areEqualWithinPrecision(1341.2357, 1341.235346, 4)); // false
// System.out.println(areEqualWithinPrecision(0.2357, 0.235346, 4)); // false
//
// System.out.println(areEqualWithinPrecision(0.2357, 0.235346)); // true
}
}

Footer

@Khushank1120
Copy link

It needs to return true if two double numbers are the same up to three decimal places. Otherwise, returns false.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment