简体   繁体   中英

Java dots and commas at decimals

My program only accepts dots when accepting decimals; I'd like it to also accept commas.

I don't want to replace the dot with a comma; instead, I want to make it accept both dots and commas. I need to apply it to the String "amount" which is converted to a double afterwards! How can I do that?

    public static void main(String[] args){
    
        double euro, usd, gpb, dkk, done;
        
        Scanner input = new Scanner(System.in);
    
        String temp = JOptionPane.showInputDialog("Convert from " +"USD, GBP, DKK or EURO?");
        
        String tempp = JOptionPane.showInputDialog("To " +"USD, GBP, DKK or EURO?");
    
        Map<String, Double> lookUpMap = new HashMap<String, Double>(){{
            put("EURO", new Double(7.46));
            put("USD", new Double(5.56));
            put("GBP", new Double(8.84));
            put("DKK", new Double (1.0));
            }};
        
        
        String amount = JOptionPane.showInputDialog("amount of " +(temp));
        double amountt = Double.parseDouble(amount);
        done = (lookUpMap.get(temp.toUpperCase()) / lookUpMap.get(tempp.toUpperCase())) * amountt;
        
        JOptionPane.showMessageDialog(null, "It is " +done + " " +(temp),"Final amount of " + (temp), JOptionPane.PLAIN_MESSAGE);
        
        String exit = JOptionPane.showInputDialog("Do u want to rerun program? YES or NO");
        if(exit.equalsIgnoreCase("YES")){
            RerunGUI.main(args);
        }else{
            System.out.println("");
        }

    }

}

If you want to parse a dollar value that has commas and decimals you can use NumberFormat And use a locale that uses that number format.

     String value1 = "1,222.34";
     String value2 = "2,334.45";

     double d1 = 0;
     double d2 = 0;
     try {
        NumberFormat usFormat = NumberFormat.getNumberInstance(Locale.US);
        d1 = usFormat.parse(value1).doubleValue();
        d2 = usFormat.parse(value2).doubleValue();
     } catch(ParseException ex) {
         ex.printStackTrace();
     }

     System.out.println(d1 + d2);  // Output 3556.79

See for list of different locales.

我认为您可能想尝试对收到的值使用String.replaceAll()命令,然后将该值转换为double

double amountt = Double.parseDouble(amount.replaceAll(",","."));

This is a bit ugly, but it seems to be what you want:

double amountt = Double.parseDouble(amount.replaceAll(",",".");

this way, everything that is entered (be-it a decimal with a comma or with a point) is parsed.

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