Search code examples
javanumber-formatting

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

    }

}


Solution

  • I think that you might want to try using String.replaceAll() command on value that you receive, then cast the value into double.

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