解析字符串加倍 - java [英] Parsing string to double - java

查看:245
本文介绍了解析字符串加倍 - java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于一个项目,我有一个类似银行的程序。 银行读入一个文件,其中的帐户如下:

Miller

William

00001

891692 06 < ----需要转换为double的字符串

最后一个字符串必须转换为double,以便程序可以像加法和减法等一样对它进行计算。

而且我还要以货币形式打印出来,即$ 891692.06

For a project I have a program that is like a bank. The "bank" reads in a file with accounts in it that look like this:
Miller
William
00001
891692 06 <----string that needs to be converted to double
The last string has to be converted to a double so that the program can perform calculations on it like addition and subtraction, etc.
And also I have to print it out in monetary format, i.e. $891692.06

到目前为止我有这个:

I have this so far:

 public class Account {
      private String firstName, lastName;
      private int accountID;
      private String currentBalance; 

      private static int maxAccountID;

      public Account(String fN, String lN, int acct, String bal) {
         firstName = fN; lastName = lN;
         accountID = acct;
         currentBalance = bal;
         if(accountID > Account.maxAccountID)
            Account.maxAccountID = accountID;
      }     

  public double getBalance(){
        String [] s = currentBalance.split(" ");
        String balStr = "$"+s[0]+"."+s[1];
            double currentBalance = Double.parseDouble(balStr);
         return currentBalance;
      }
}

提前致谢!

推荐答案

如果表示 double 的字符串使用空格''而不是小数点,您可以通过用点替换空格来修复它,如下所示:

If your string representing double uses space ' ' instead of a decimal point, you can fix it by replacing the space with a dot, like this:

String currentBalanceStr = "891692 06";
double currentBalanceDbl = Double.parseDouble(currentBalanceStr.replaceAll(" ","."));

链接到ideone。

这篇关于解析字符串加倍 - java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆