简体   繁体   中英

Java issue converting String to double

I'm trying to convert a String into double.

The source string is in the format "88.6" and the double I expect should be "88.60".

I tried converting using Double.parseDouble, Double constructor, Double.valueOf, DecimalFormat and NumberFormat hardcoding Locale.US or Locale.ENGLISH but I still get "88,600000".

How should I convert it?

Thanks

DecimalFormat df = new DecimalFormat("#.##", new DecimalFormatSymbols(Locale.US));
try {
    dValue = df.parse(szValue).doubleValue();
} catch(ParseException e) {
    e.printStackTrace();
}

While I don't think that keeping trailing zeros is necessary, I think this is what you are asking for:

    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator('.');
    java.text.DecimalFormat df = new java.text.DecimalFormat();  
    df.setDecimalFormatSymbols(dfs);
    df.applyPattern( "###0.00" );
    String s = "9.90" ;
    System.out.println("non formated d=" + Double.valueOf(s) + " formated d=" +df.format(Double.valueOf(s)));   

the trailing zeros are only visible when printing them, so you just need to format the number

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