简体   繁体   中英

How to parse String, with both decimal separators comma and dot as well, to Double

I need to input number as a String from user and parse it to the Double object.

I'd like it to be available to take comma, as a decimal separator, and dot as well and save it and outuput only with a dot.

Example: 22,33-->22.33 and 22.33-->22.33

What I use is:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
        try {
            Number number = format.parse(formDto.getWeight());
            kitten.setWeight(number.doubleValue());
        } catch (ParseException e) {
            e.printStackTrace();
        }

But it only gets values with ',' separator. When user inputs with dot it loses all decimals and returns that 22.33 -->22.0 or 4.1 --> 4.0 When i debug i see that it's a parsing problem (obvious) but have no idea what is good practice to solve it.

You can replace the dot "." with comma :," before the parsing.

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
    try {
        Number number = format.parse(formDto.replace('.', ',').getWeight());
        kitten.setWeight(number.doubleValue());
    } catch (ParseException e) {
        e.printStackTrace();
    }

Like Mohit Thakur said, but compilable.

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
try {
    Number number = format.parse(formDto.getWeight().replace('.', ','));
    kitten.setWeight(number.doubleValue());
} catch (ParseException e) {
    e.printStackTrace();
}

Once try with this:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
        try {
           Number number = Double.parseDouble(format.replace(",", ".").getWeight());
            kitten.setWeight(number.doubleValue());
        } catch (ParseException e) {
            e.printStackTrace();
        }

Thanks.

If you just want to convert your String to Double value then it can be done with the below approach

String numberStr1 = "22,33"; //number with comma as decimal separator
String numberStr2 = "22.33"; //number with dot as decimal separator

System.out.println(numberStr1.contains(",") ? Double.valueOf(numberStr1.replace(',', '.')):Double.valueOf(numberStr1));
System.out.println(numberStr2.contains(",") ? Double.valueOf(numberStr2.replace(',', '.')):Double.valueOf(numberStr2));

I have used Java Tertiary Operator to achieve this task. You can store the double value instead of printing to screen.

If this does not help or you want to do it specifically with NumberFormat then do let me know in comments.

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