How to check if a number has decimal places to the thousandths place or more?

375 Views Asked by At

I am working on a program that prints out the wages earned by workers including overtime pay. I am almost finished with the program. However, I am stuck on how to make a condition to fix the decimals in the wages to only the tenths and hundredths places (.00).

The condition I want is, if the number of hours worked is greater than 40 and the overtime wages have numbers in the thousandths place or more (overTimeWages has .000 or more .0000000000....), then System.out.println("$" + (Math.floor(overTimeWages * 100) / 100)); to round overTimeWages to the nearest hundredths down. I only want the tenths and hundredths place values. Else if hours worked is greater than 40 and the overtime wages have numbers only in the tenths and hundredths place, then System.out.println("$" + overTimeWages + 0);.

How do I make that condition above?

I tried overTimeWages % 0.1 != 0; but it did not work.

Below in the code comments are the values that are supposed to be inputted.

Code

import java.util.Scanner;

int payRateInCents, payRateInDollars,
    hoursWorked, 
    overTimeHours, grossPayWithInt;
  
double grossPay, payRCents, payRDollars, overTimeRate;

grossPay = (double) ((payRDollars * hoursWorked));
grossPayWithInt = (payRateInCents * 40);
double grossPayWithOverTime = (double) ((grossPayWithInt) + (overTimeRate * overTimeHours));
double overTimeWages = (double) (grossPayWithOverTime / 100);

/**
   2000 45 = (2000 * 40) + ((2000 * 1.5) * (45 - 40)) == 95000
   2000 45 = (grossPayWithOverTime) + ((overTimeRate) * (overTimeHours)) == 95000
   Then divide by 100.
   
   2000 40 should get: $800.00
   1640 41 should get: $680.60
   3111 43 should get: $1384.39
   1005 1 should get: $10.05
  **/

if(hoursWorked > 40) {
    if(overTimeWages % 0.1 != 0) {
      System.out.println("$" + (Math.floor(overTimeWages * 100) / 100));
    } else {
      System.out.println("$" + overTimeWages + 0);
    }
  }
  
  else {
    if(hoursWorked < 10) {
      System.out.println("$" + grossPay);
    } else {
      System.out.println("$" + grossPay + 0);//40 or lower
    }
  }

1

There are 1 best solutions below

5
On

Dont use fractions or float for any variables that will hold money. Operations on float will give you unexpected result due to how floats are stored. You think 1.2 is 1.2 but it might be actually 1.19999999. That's how floats work. I would suggest to not get into any fractions when dealing with money. Instead of 1.30$ use 130 cents.

For displaying purposes converting it is trivial:

private static DecimalFormat df = new DecimalFormat("#.##");
Syste.out.println(df.format(yourDouble));

To see how many decimals number has.

String[] split = yourDouble.toString().split("\\.");
split[0].length();   
split[1].length();