格式化java中I / O文件中的双值...

时间:2013-11-18 21:38:00

标签: java

请如何将此程序中updatedsalary的值格式化为2位小数???

     package elapsedTime;
import java.io.*;
import java.util.*;
public class Salary {

public static void main(String[] args)throws FileNotFoundException {
    String firstname,lastname;
    double currentSalary, PayIncrease;
    double updatedsalary;
Scanner infile=new Scanner(new FileReader("Ch3_Ex7Data.txt"));
PrintWriter Outfile=new PrintWriter("Outdata.dat");
    firstname=infile.next();
    lastname=infile.next();
    currentSalary=infile.nextDouble();
    PayIncrease=infile.nextDouble();
    updatedsalary=((PayIncrease*currentSalary)/100)+currentSalary;
Outfile.printf("FIRSTNAME:"+firstname+"\n"+"LASTNAME:"+lastname+"\n"+"UPDATEDSALARY:"+updatedsalary+"\n"+"\n");
firstname=infile.next();
lastname=infile.next();
currentSalary=infile.nextDouble();
PayIncrease=infile.nextDouble();
updatedsalary=((PayIncrease*currentSalary)/100)+currentSalary;
Outfile.printf("FIRSTNAME:"+firstname+"\n"+"LASTNAME:"+lastname+"\n"+"UPDATEDSALARY:"+updatedsalary+"\n"+"\n");
firstname=infile.next();
lastname=infile.next();
currentSalary=infile.nextDouble();
PayIncrease=infile.nextDouble();
updatedsalary=((PayIncrease*currentSalary)/100)+currentSalary;
Outfile.printf("FIRSTNAME:"+firstname+"\n"+"LASTNAME:"+lastname+"\n"+"UPDATEDSALARY:"+updatedsalary+"\n"+"\n");
infile.close();
Outfile.close();
}

}  我对在Outfile.printf语句中使用格式说明符的位置感到困惑。

2 个答案:

答案 0 :(得分:0)

你可能正在寻找Decimal Format。 你会做类似

的事情
double d = 2.34568;
DecimalFormat f = new DecimalFormat("##.00");
Outfile.printf(f.format(d));

答案 1 :(得分:0)

您可以使用此行代码将薪水打印到2位小数:

Outfile.printf("FIRSTNAME:"+firstname+"\n"+"LASTNAME:"+lastname+"\n"+"UPDATEDSALARY:%.2f\n"+"\n", updatedsalary);