views:

2063

answers:

4

Hi, What is the easiest and correct way to convert a String number with commas (for example: 835,111.2) to a Double instance.

Thanks, Rod

+15  A: 

Have a look at java.text.NumberFormat. For example:

import java.text.*;
import java.util.*;

public class Test
{
    // Just for the sake of a simple test program!
    public static void main(String[] args) throws Exception
    {
        NumberFormat format = NumberFormat.getInstance(Locale.US);

        Number number = format.parse("835,111.2");
        System.out.println(number); // or use number.doubleValue()
    }
}

Depending on what kind of quantity you're using though, you might want to parse to a BigDecimal instead. The easiest way of doing that is probably:

BigDecimal value = new BigDecimal(str.replace(",", ""));

or use a DecimalFormat with setParseBigDecimal(true):

DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
format.setParseBigDecimal(true);
BigDecimal number = (BigDecimal) format.parse("835,111.2");
Jon Skeet
Are you sure `NumberFormat.getInstance` will always return instance of `DecimalFormat`. And doesn't manual replacing commas with dots defeat the whole idea of localization?
Tadeusz Kopec
@Tadeusz: The question is specifically about "numbers with commas" - not "numbers in the current locale". When the question is specific, it makes sense for the answer to be specific. As for NumberFormat.getInstance potentially not returning DecimalFormat - yes, that's a possibility. I'm not sure the best way round that, to be honest; the API isn't particularly useful there :(
Jon Skeet
+4  A: 

Use java.text.DecimalFormat:

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.

skaffman
+2  A: 

The easiest is not always the most correct. Here's the easiest:

String s = "835,111.2";
// NumberFormatException possible.
Double d = Double.parseDouble(s.replaceAll(",",""));

I haven't bothered with locales since you specifically stated you wanted commas replaced so I'm assuming you've already established yourself as a locale with comma is the thousands separator and the period is the decimal separator. There are better answers here if you want correct (in terms of internationalization) behavior.

paxdiablo