如何使用特定的语言环境在Java中将String转换为Double?

时间:2021-07-09 07:27:22

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?

我想将我得到的一些数字转换为双打,但这些数字不是美国标准语言环境,而是另一个数字。我怎样才能做到这一点?

8 个解决方案

#1


61  

Try java.text.NumberFormat. From the Javadocs:

试试java.text.NumberFormat。来自Javadocs:

To format a number for a different Locale, specify it in the call to getInstance.

要格式化不同Locale的数字,请在对getInstance的调用中指定它。

NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);

You can also use a NumberFormat to parse numbers:

您还可以使用NumberFormat来解析数字:

myNumber = nf.parse(myString);

parse() returns a Number; so to get a double, you must call myNumber.doubleValue():

parse()返回一个Number;所以要获得双倍,你必须调用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.

请注意,parse()永远不会返回null,因此这不会导致NullPointerException。相反,如果失败,解析将抛出一个已检查的ParseException。

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!

编辑:我原来说有另一种转换为double的方法:将结果转换为Double并使用拆箱。我认为,由于正在使用NumberFormat的通用实例(根据getInstance的Javadoc),它总是返回一个Double。但是DJClayworth指出,用于解析的Javadocs(String,ParsePosition)(由parse(String)调用)表示如果可能的话返回Long。因此,将结果转换为Double是不安全的,不应该尝试!谢谢,DJClayworth!

#2


5  

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.

NumberFormat是可行的方法,但是当你的数据小于100%正确时,你应该意识到它的特殊性。

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.

如果您的输入可以信任,那么您不必担心它。

#3


3  

You use a NumberFormat. Here is one example, which I think looks correct.

您使用NumberFormat。这是一个例子,我认为看起来是正确的。

#4


3  

Just learning java and programming. Had similar question. Found something like this in my textbook:

只是学习java和编程。有类似的问题。在我的教科书中找到这样的东西:

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.

该书说,扫描程序会自动解码String变量中的内容,并且Scanner类会自动适应所设置Locale的语言,系统Locale是默认设置,但这很容易设置为其他内容。

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.

另外:我喜欢这种方法的原因是,当使用swing dialouge box进行输入然后尝试将字符串转换为带解析的double时,我得到了一个N​​umberFormatException。事实证明,解析专门使用美国数字格式,而扫描程序可以处理所有格式。即使使用逗号(,)小数分隔符,Scanner也能使输入完美无缺。由于最多的投票答案使用解析我真的不知道它将如何解决这个特定的问题。您必须以美国格式输入数字,然后将其转换为您的语言环境格式。当一个数字键盘配有逗号时,这是相当不方便的。

Now you're all free to shred me to pieces ;)

现在你可以*地把我撕碎了;)

#5


1  

This should be no problem using java.text.DecimalFormat.

使用java.text.DecimalFormat应该没有问题。

#6


1  

Use NumberFormat.getNumberInstance(Locale)

#7


0  

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.

这甚至适用于科学记数法,带百分号的字符串或带有货币符号的字符串。

#8


-3  

Here is how you use parseDouble to convert a String to a Double:

以下是使用parseDouble将String转换为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);
        }
}

#1


61  

Try java.text.NumberFormat. From the Javadocs:

试试java.text.NumberFormat。来自Javadocs:

To format a number for a different Locale, specify it in the call to getInstance.

要格式化不同Locale的数字,请在对getInstance的调用中指定它。

NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);

You can also use a NumberFormat to parse numbers:

您还可以使用NumberFormat来解析数字:

myNumber = nf.parse(myString);

parse() returns a Number; so to get a double, you must call myNumber.doubleValue():

parse()返回一个Number;所以要获得双倍,你必须调用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.

请注意,parse()永远不会返回null,因此这不会导致NullPointerException。相反,如果失败,解析将抛出一个已检查的ParseException。

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!

编辑:我原来说有另一种转换为double的方法:将结果转换为Double并使用拆箱。我认为,由于正在使用NumberFormat的通用实例(根据getInstance的Javadoc),它总是返回一个Double。但是DJClayworth指出,用于解析的Javadocs(String,ParsePosition)(由parse(String)调用)表示如果可能的话返回Long。因此,将结果转换为Double是不安全的,不应该尝试!谢谢,DJClayworth!

#2


5  

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.

NumberFormat是可行的方法,但是当你的数据小于100%正确时,你应该意识到它的特殊性。

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.

如果您的输入可以信任,那么您不必担心它。

#3


3  

You use a NumberFormat. Here is one example, which I think looks correct.

您使用NumberFormat。这是一个例子,我认为看起来是正确的。

#4


3  

Just learning java and programming. Had similar question. Found something like this in my textbook:

只是学习java和编程。有类似的问题。在我的教科书中找到这样的东西:

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.

该书说,扫描程序会自动解码String变量中的内容,并且Scanner类会自动适应所设置Locale的语言,系统Locale是默认设置,但这很容易设置为其他内容。

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.

另外:我喜欢这种方法的原因是,当使用swing dialouge box进行输入然后尝试将字符串转换为带解析的double时,我得到了一个N​​umberFormatException。事实证明,解析专门使用美国数字格式,而扫描程序可以处理所有格式。即使使用逗号(,)小数分隔符,Scanner也能使输入完美无缺。由于最多的投票答案使用解析我真的不知道它将如何解决这个特定的问题。您必须以美国格式输入数字,然后将其转换为您的语言环境格式。当一个数字键盘配有逗号时,这是相当不方便的。

Now you're all free to shred me to pieces ;)

现在你可以*地把我撕碎了;)

#5


1  

This should be no problem using java.text.DecimalFormat.

使用java.text.DecimalFormat应该没有问题。

#6


1  

Use NumberFormat.getNumberInstance(Locale)

#7


0  

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.

这甚至适用于科学记数法,带百分号的字符串或带有货币符号的字符串。

#8


-3  

Here is how you use parseDouble to convert a String to a Double:

以下是使用parseDouble将String转换为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);
        }
}