I want to convert some numbers which I got as strings into Doubles, but these numbers are not in US standard locale, but in a different one. How can I do that?
Try java.text.NumberFormat
. From the Javadocs:
To format a number for a different Locale, specify it in the call to getInstance.
NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
You can also use a NumberFormat to parse numbers:
myNumber = nf.parse(myString);
parse()
returns a Number
; so to get a double
, you must call myNumber.doubleValue()
:
double myNumber = nf.parse(myString).doubleValue();
Note that parse()
will never return null
, so this cannot cause a NullPointerException
. Instead, parse
throws a checked ParseException
if it fails.
Edit: I originally said that there was another way to convert to double
: cast the result to Double
and use unboxing. I thought that since a general-purpose instance of NumberFormat
was being used (per the Javadocs for getInstance
), it would always return a Double
. But DJClayworth points out that the Javadocs for parse(String, ParsePosition)
(which is called by parse(String)
) say that a Long
is returned if possible. Therefore, casting the result to Double
is unsafe and should not be tried!
Thanks, DJClayworth!
NumberFormat is the way to go, but you should be aware of its peculiarities which crop up when your data is less than 100% correct.
I found the following usefull:
http://www.ibm.com/developerworks/java/library/j-numberformat/index.html
If your input can be trusted then you don't have to worry about it.
Just learning java and programming. Had similar question. Found something like this in my textbook:
Scanner sc = new Scanner(string);
double number = sc.nextDouble();
The book says that a scanner automatically decodes what's in a String variabel and that the Scanner class automatically adapts to the language of the set Locale, system Locale being the default, but that's easy to set to something else.
I solved my problem this way. Maybe this could work for the above issue instead of parsing?
Addition: The reason I liked this method was the fact that when using swing dialouge boxes for input and then trying to convert the string to double with parse I got a NumberFormatException. It turned out that parse exclusively uses US-number formatting while Scanner can handle all formats. Scanner made the input work flawlessly even with the comma (,) decimal separator. Since the most voted up answer uses parse I really don't see how it would solve this particular problem. You would have to input your numbers in US format and then convert them to your locale format. That's rather inconvenient when ones numeric keybord is fitted with a comma.
Now you're all free to shred me to pieces ;)
A parser that parses a text string of primitive types and strings with the help of regular expressions. This class is not as useful as it might seem. It's very inefficient for communicating between machines; you should use JSON, protobufs, or even XML for that. Very simple uses might get away with String#split. For input from humans, the use of locale-specific regular expressions make it not only expensive but also somewhat unpredictable.
–
Netsuke You use a NumberFormat
. Here is one example, which I think looks correct.
This should be no problem using java.text.DecimalFormat.
Do you know which locale it is? Then you can use
DecimalFormat format = DecimalFormat.getInstance(theLocale);
format.parse(yourString);
this will even work for scientific notations, strings with percentage signs or strings with currency symbols.
Here is how you use parseDouble
to convert a String
to a Double
:
doubleExample.java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class doubleExample {
public static void main(String[] args) {
Double myDouble = new Double("0");
System.out.println("Please enter a number:");
try
{
//get the number from console
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
myDouble = Double.parseDouble(br.readLine());
}
//if invalid value was entered
catch(NumberFormatException ne)
{
System.out.println("Invalid value" + ne);
System.exit(0);
}
catch(IOException ioe)
{
System.out.println("IO Error :" + ioe);
System.exit(0);
}
System.out.println("Double value is " + myDouble);
}
}
parseDouble
uses the same rules as valueOf
, which are Java Language double format. That means it won't parse 1,0
as double, no matter the current locale. And, furthermore, there's no way to pass a specific locale, as asked for (which makes sense, since it doesn't use locale at all). –
Clangor © 2022 - 2024 — McMap. All rights reserved.