简体   繁体   中英

how to round the answer in two decimal point

I have simple math example Add, Substract, Divide and Multiply and using variable as double and want answer should be in two decimal point if I use decimals to add substract divide or multiply.

    private void jButton_addActionPerformed(java.awt.event.ActionEvent  
    evt)    {                                            

    double First = Double.parseDouble(jTextField1.getText());
    // Read the Second number
    double Second = Double.parseDouble(jTextField2.getText());
    // Set the Result
    double Result = First + Second;

    jLabel4.setText(String.valueOf(Result));
     }                                           

    private void jButton_substractActionPerformed
   (java.awt.event.ActionEvent evt)   
   {                                                  

    double First = Double.parseDouble(jTextField1.getText());
   // Read the Second number
   double Second = Double.parseDouble(jTextField2.getText());
   // Set the Result
   double Result = First - Second;


   jLabel4.setText(String.valueOf(Result));
   }                                                 

    private void jButton_MultiplyActionPerformed  
   (java.awt.event.ActionEvent  evt)   
   {                                                 

    double First = Double.parseDouble(jTextField1.getText());
    // Read the Second number
    double Second = Double.parseDouble(jTextField2.getText());
    // Set the Result
    double Result = First * Second;


    jLabel4.setText(String.valueOf(Result));

  }                                                

   private void jButton_divideActionPerformed(java.awt.event.ActionEvent 
    evt)   {                                               

    double First = Double.parseDouble(jTextField1.getText());
    // Read the Second number
    double Second = Double.parseDouble(jTextField2.getText());
    // Set the Result
    double Result = First / Second;


    jLabel4.setText(String.valueOf(Result));
    }                                              

How to get result rounded to two decimal Points like 12.38 instead of 12.379999

使用setRoundingMode告诉它您想要多少个小数点。

You can do this by

double round = Math.round(number * 100.0) / 100.0;

where number is your decimal number

To break it down -

double number = 3.14159;
number = Math.round(number * 100);
number = number/100;

The output will be 3.14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM