我目前有 switch 语句,可以根据 worker 的头衔随机生成工资。一切工作正常,但我似乎无法正确截断工资。
无论如何,我需要工资以两位小数结尾。它适用于像“57662.24”这样的工资,但我也得到像“87756.4”这样的工资,我需要是“87756.40”
我不确定我做错了什么,所以我希望能得到一些帮助!
// 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));
}
最佳答案
更改方法,使其返回由 DecimalFormat
对象格式化的 String
。
private static String salary(double sal) {
DecimalFormat df = new DecimalFormat("###.00");
return (df.format(sal));
}
您费尽心思对其进行格式化,然后再次将其设为Double
,您就白费了功夫。
关于JAVA:使用 DecimalFormat 时遇到问题?需要 30.40 而不是 30.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42965306/