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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/888088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 20:42:29  来源:igfitidea点击:

How do I convert a String to Double in Java using a specific locale?

javalocalization

提问by Daniel C. Sobral

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?

我想将我作为字符串获得的一些数字转换为双精度数,但这些数字不在美国标准语言环境中,而是在不同的语言环境中。我怎样才能做到这一点?

采纳答案by Michael Myers

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.

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

You can also use a NumberFormat to parse numbers:

myNumber = nf.parse(myString);

要为不同的区域设置格式化数字,请在对 getInstance 的调用中指定它。

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

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

myNumber = nf.parse(myString);

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

parse()返回一个Number; 所以要得到一个double,你必须打电话myNumber.doubleValue()

    double myNumber = nf.parse(myString).doubleValue();

Note that parse()will never return null, so this cannot cause a NullPointerException. Instead, parsethrows a checked ParseExceptionif it fails.

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

Edit:I originally said that there was another way to convert to double: cast the result to Doubleand use unboxing. I thought that since a general-purpose instance of NumberFormatwas being used (per the Javadocs for getInstance), it would always return a Double. But DJClayworthpoints out that the Javadocs for parse(String, ParsePosition)(which is called by parse(String)) say that a Longis returned if possible. Therefore, casting the result to Doubleis unsafe and should not be tried!
Thanks, DJClayworth!

编辑:我最初说有另一种方法可以转换为double:将结果转换为Double并使用拆箱。我认为由于NumberFormat正在使用的通用实例(根据 Javadocs for getInstance),它总是会返回一个Double. 但是DJClayworth指出 for parse(String, ParsePosition)(由 调用parse(String))的 Javadoc说Long如果可能的话会返回a 。因此,将结果转换Double为不安全,不应尝试!
谢谢,DJ克莱沃思!

回答by Roland Ewald

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

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

回答by unwind

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

你使用一个NumberFormat. 是一个例子,我认为它看起来是正确的。

回答by adrian.tarau

Use NumberFormat.getNumberInstance(Locale)

使用 NumberFormat.getNumberInstance(Locale)

回答by Fortega

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.

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

回答by Jasper Floor

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

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.

如果您的输入是可信的,那么您就不必担心。

回答by bjarun

Here is how you use parseDoubleto convert a Stringto a Double:

以下是parseDouble将 a 转换String为 a 的方法Double

doubleExample.java

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

回答by lytwaytLaz

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.

这本书说扫描器会自动解码字符串变量中的内容,并且 Scanner 类会自动适应设置的语言环境,系统语言环境是默认设置,但很容易设置为其他内容。

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 对话框进行输入,然后尝试使用解析将字符串转换为 double 时,我得到了一个 NumberFormatException。原来 parse 只使用 US-number 格式,而 Scanner 可以处理所有格式。即使使用逗号 (,) 小数点分隔符,扫描仪也使输入工作完美无缺。由于投票最多的答案使用 parse 我真的不知道它会如何解决这个特定问题。您必须以美国格式输入您的数字,然后将它们转换为您的语言环境格式。当数字键盘带有逗号时,这很不方便。

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

现在你们都可以把我撕成碎片了 ;)