0

How do I convert a string such as 40,123.012345678901 to a double?

double d = Double.parseDouble("40,123.012345678901"); 

throws a number format exception.

Thanks

SatyaTNV
  • 4,137
  • 3
  • 15
  • 31
S M
  • 1
  • 1
  • Did you tried to remove the "," in the Double string? – Marcel Oct 26 '15 at 18:30
  • 4
    Possible duplicate of [Best way to parseDouble with comma as decimal separator?](http://stackoverflow.com/questions/4323599/best-way-to-parsedouble-with-comma-as-decimal-separator) – ccc Oct 26 '15 at 18:44

5 Answers5

2

If there is no way to get rid of comma(,) you may use another approach:

NumberFormat format = NumberFormat.getInstance(Locale.US);
Number number = format.parse("40,123.012345678901");
double d = number.doubleValue();
algor
  • 404
  • 2
  • 8
1

The simplest way is to remove comma:

double d = Double.parseDouble("40,123.012345678901".replace(",", "")); 
hsz
  • 148,279
  • 62
  • 259
  • 315
1

A double is limited to around 16 digits of precision. If you need more precision, you should use BigDecimal.

BigDecimal bd = new BigDecimal("40,123.012345678901".replace(",", "")); 
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

You should remove the comma (,) from your string:

This will work:

double d = Double.parseDouble("40123.012345678901"); 
Prem
  • 157
  • 7
0

Use NumberFormat to get double value,

    try {
        NumberFormat format = NumberFormat.getInstance();
        Number parse = format.parse("40,123.012345678901");
        System.out.println(parse.doubleValue());
    } catch (ParseException ex) {
        System.out.println(ex.getMessage());
    }
ccc
  • 370
  • 5
  • 19