Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a String to Double - Java

Tags:

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

Thanks.

like image 418
Rod Avatar asked Jul 08 '09 10:07

Rod


People also ask

Which function will convert a String into a double?

In the C Programming Language, the strtod function converts a string to a double. The strtod function skips all white-space characters at the beginning of the string, converts the subsequent characters as part of the number, and then stops when it encounters the first character that isn't a number.

What does double parseDouble do in java?

parseDouble. Returns a new double initialized to the value represented by the specified String , as performed by the valueOf method of class Double .


2 Answers

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"); 
like image 127
Jon Skeet Avatar answered Oct 10 '22 10:10

Jon Skeet


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.

like image 22
paxdiablo Avatar answered Oct 10 '22 11:10

paxdiablo