25

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

Thanks.

Anderson Green
  • 30,230
  • 67
  • 195
  • 328
Rod
  • 2,180
  • 2
  • 20
  • 23

5 Answers5

47

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 1
    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 for Ukraine Mar 10 '10 at 09:19
  • 1
    @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 Mar 10 '10 at 09:22
10

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
  • 854,327
  • 234
  • 1,573
  • 1,953
5

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
  • 398,947
  • 96
  • 818
  • 769
2

A link can say more than thousand words

// Format for CANADA locale
Locale locale = Locale.CANADA;
String string = NumberFormat.getNumberInstance(locale).format(-1234.56);  // -1,234.56

// Format for GERMAN locale
locale = Locale.GERMAN;
string = NumberFormat.getNumberInstance(locale).format(-1234.56);   // -1.234,56

// Format for the default locale
string = NumberFormat.getNumberInstance().format(-1234.56);


// Parse a GERMAN number
try {
    Number number = NumberFormat.getNumberInstance(locale.GERMAN).parse("-1.234,56");
    if (number instanceof Long) {
        // Long value
    } else {
        // Double value
    }
} catch (ParseException e) {
}
Tim Büthe
  • 62,884
  • 17
  • 92
  • 129
  • Good point, used the [way back machine](http://web.archive.org/web/20110702052222/http://exampledepot.com/egs/java.text/Numbers.html) and copied the example – Tim Büthe Dec 03 '12 at 15:02
1
    There is small method to convert german price format
    public static BigDecimal getBigDecimalDe(String preis) throws ParseException {
        NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
        Number number = nf.parse(preis);
        return new BigDecimal(number.doubleValue());
    }
  ----------------------------------------------------------------------------  
    German format BigDecimal Preis into decimal format
  ----------------------------------------------------------------------------  
    public static String decimalFormat(BigDecimal Preis){       
        String res = "0.00";
                    if (Preis != null){                 
                        NumberFormat nf = NumberFormat.getInstance(Locale.GERMANY);
                        if (nf instanceof DecimalFormat) {                      
                             ((DecimalFormat) nf).applyPattern("###0.00");

                             }
                            res =    nf.format(Preis);                                  
                    }
            return res;

        }
---------------------------------------------------------------------------------------
/**
 * This method converts Deutsche number format into Decimal format.
 * @param Preis-String parameter.
 * @return
 */
public static BigDecimal bigDecimalFormat(String Preis){        
    //MathContext   mi = new MathContext(2);
    BigDecimal bd = new BigDecimal(0.00);
                if (!Util.isEmpty(Preis)){  
                    try {
//                      getInstance() obtains local language format
                    NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);  
                     nf.setMinimumFractionDigits(2);
                     nf.setMinimumIntegerDigits(1);
                     nf.setGroupingUsed(true);


                    java.lang.Number    num = nf.parse(Preis);
                    double d = num.doubleValue();
                         bd = new BigDecimal(d);
                    } catch (ParseException e) {                        
                        e.printStackTrace();
                    }                       
                }else{
                     bd = new BigDecimal(0.00);
                }

                //Rounding digits 
        return bd.setScale(2, RoundingMode.HALF_UP);

    }
Narayan Yerrabachu
  • 1,714
  • 1
  • 19
  • 31