首页 > 解决方案 > Java将字符串转换为双精度

问题描述

我创建了一个基本的 GUI,它获取用户输入的金额并用预先存在的金额减去它。但是它不会让我运行下面的那个,因为我得到一个错误,字符串不能转换为双精度。使用 parseInt 方法在这里不起作用,因为我使用 getText 方法。

String message = txtaMessage.getText();
    String transaction1 = txtfAmountTransfer.getText();
    String reciever = txtfTransferTo.getText();
    
    lblOutputTransferInfo.setText("Your Amount of "+transaction1+" has been sent to "+reciever+" .");
    lblOutputTransferMsg.setText("With a Message: "+ message);

   double balance = 5123.84;
   
   String newBalance = balance - transaction1;//this will not work but the concept I need 
   
   lblSavingsBalance.setText(newBalance);

标签: java

解决方案


它不起作用,因为这里的 transcation1 是一个字符串,而 balance 是双倍的。在java中,我们没有从double中减去字符串的方法。所以,首先,你需要转换transaction1成双精度。我建议你 Double newBalance = balance - Double.parseDouble(transcation1); 然后lblSavingsBalance.setText(newBalance.toString());newBalance双精度值转换为字符串

希望它工作正常...


推荐阅读