我有简单的数学例子Add,Substract,Divide和Multiply,并且使用变量作为double,如果我使用小数来添加减法或乘法,则想要答案应该是两位小数。
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));
}
如何将结果舍入为两个小数点,如12.38而不是12.379999
答案 0 :(得分:0)
使用setRoundingMode告诉它你想要多少小数点。
答案 1 :(得分:-1)
您可以通过
执行此操作double round = Math.round(number * 100.0) / 100.0;
其中number
是您的十进制数
要打破它 -
double number = 3.14159;
number = Math.round(number * 100);
number = number/100;
输出为3.14