如何将数据值设置为小数点后三位



这个应用程序即将结束,但我需要输出文件的输出数据值在小数点后三位。到目前为止,最终输出是我需要的(资产文件中数据值的平方根)。这是我为应用程序编写的代码:

public void srAndSave(View view)
{
    EditText edt1;
    EditText edt2;
    TextView tv;
    String infilename; 
    String outfilename;
    tv = (TextView) findViewById(R.id.text_status);
    //Get the name of the input file and output file
    edt1 = (EditText) findViewById(R.id.edit_infile);
    edt2 = (EditText) findViewById(R.id.edit_outfile);
    infilename = edt1.getText().toString();
    outfilename = edt2.getText().toString();
    //Create an array that stores double values (up to 20)
    double double_nums[] = new double[20];
    int n = 0;//For storing the number of data values in the array

    //Open the data file from the asset directory
    //and make sure the data file exists
    AssetManager assetManager = getAssets();
    try
    {
        Scanner fsc = new Scanner(assetManager.open(infilename));
        //Get the data values from the file
        //and store them in the array double_nums
        n = 0;
        while(fsc.hasNext()){
            double_nums[n] = fsc.nextDouble();
            n++;
        }
        //Calls on square_root_it method
        square_root_it(double_nums, n);
        //Display that the file has been opened
        tv.setText("Opening the input file and reading the file were "
                + " successful.");
        fsc.close();
    }
    catch(IOException e)
    {
        tv.setText("Error: File " + infilename + " does not exist");
    }
    //Write the data to the output file and
    //also make sure that the existence of the file
    File outfile = new File(getExternalFilesDir(null), outfilename);
    try
    {
        FileWriter fw = new FileWriter(outfile); 
        BufferedWriter bw = new BufferedWriter(fw);
        PrintWriter pw = new PrintWriter(bw); 
        int x;
        for(x=0;x < n;x++)
            pw.println(double_nums[x]); //Write the data values that are stored in
                                        //the array, double_nums after the method call
                                        //for square_root_it
        pw.close();
    }
    catch(IOException e)
    {
        System.out.println("Error! Output file does already exist! You will overwrite"
                + " this file!");
    }
} //end srAndSave
public static void square_root_it(double[] a, int num_items)
{
    int i;
    for(i=0; i < num_items; i++)
        a[i] = Math.sqrt(a[i]); //Initialize the array a[i] to have the square root of
                                //the double values stored in double_nums[] array, and
                                //then return a[i]

} //end square_root_it

您可以格式化双精度,指定小数位数如下:

    double d = 1.234567;
    DecimalFormat df = new DecimalFormat("#.###");
    System.out.print(df.format(d));

最新更新