Rod
Rod

Reputation: 2170

Convert a String to Double - Java

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

Thanks.

Upvotes: 25

Views: 66810

Answers (5)

Narayan Yerrabachu
Narayan Yerrabachu

Reputation: 1823

    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);

    }

Upvotes: 1

Tim Büthe
Tim Büthe

Reputation: 63734

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) {
}

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499770

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");

Upvotes: 47

paxdiablo
paxdiablo

Reputation: 881093

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.

Upvotes: 10

skaffman
skaffman

Reputation: 403441

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.

Upvotes: 5

Related Questions