0

I currently have switch statements that randomly generate a salary based on the title of a worker. Everything works fine but I just can't seem to truncate the salaries correctly.

I need salaries to end with two decimals no matter what. It works with salaries like "57662.24" but I also get salaries like "87756.4" which I need to be "87756.40"

I'm not sure what I'm doing wrong so I'm hoping I can get some help!

// Method to return salary based on rank
private static Double salary(String rank) {

    // initialize variables for use in switch statement
    double sal = 0;
    Random random = new Random();
    DecimalFormat df = new DecimalFormat("###.00");

    switch (rank) {
    case "Assistant":
        sal = random.nextDouble() * (80000 - 50000) + 50000;
        break;

    case "Associate":
        sal = random.nextDouble() * (110000 - 60000) + 60000;
        break;

    case "Full":
        sal = random.nextDouble() * (130000 - 75000) + 75000;
        break;
    }
    return sal = Double.valueOf(df.format(sal));
}
4castle
  • 32,613
  • 11
  • 69
  • 106
TheDingo
  • 59
  • 6

2 Answers2

1

Change the method so that it returns the String as formatted by the DecimalFormat object.

 private static String salary(double sal) {

    DecimalFormat df = new DecimalFormat("###.00");

    return (df.format(sal));
 }

You go to the effort of formatting it, then you lose that effort by making it a Double again.

4castle
  • 32,613
  • 11
  • 69
  • 106
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

What you want is

DecimalFormat df = new DecimalFormat("#.00"); 
Fangxing
  • 5,716
  • 2
  • 49
  • 53