简体   繁体   中英

Parsing string to double - java

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, ie $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;
      }
}

Thanks in advance!

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(" ","."));

Link to ideone.

Using Double for balance calculation is not a good idea, it makes more sense to use the BigDecimal because it is more precise.

You can also add the currency using the class bellow:

Locale enUSLocale =
    new Locale.Builder().setLanguage("en").setRegion("US").build();

Currency currencyInstance = Currency.getInstance(enUSLocale);

System.out.println(
    "Symbol for US Dollar, en-US locale: " +
    currencyInstance.getSymbol(enUSLocale));

please go through this link for more details.

看起来你在做一些货币计算,所以总是使用 BigDecimal

BigDecimal balStr = new BigDecimal(String.replaceAll(" ",".");
String s="891692 06";
Double.parseDouble(s.replace(" ", ".")); would do the trick

You can use NumberFormatClass from the API to get the monetary information.

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