我如何在 Java 中读取双精度值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2240851/
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
How do I read in a double in Java?
提问by Jeff
I am trying to get a decimal input from the keyboard, and it is just not working. First I tried
我正在尝试从键盘获取十进制输入,但它不起作用。首先我试过
double d = Integer.parseInt(JOptionPane.showInputDialog(
"Please enter a number between 0 and 1:"));
and that obviously didn't work very well.
这显然效果不佳。
I am used to just parsing int's as they come in from the keyboard right into a variable, but I don't know what I am supposed to do for decimals! I need to be able to take a decimal like .9 straight from the keyboard and be able to have it in a variable I can do calculations with.
我习惯于将 int 从键盘传入时解析为变量,但我不知道我应该为小数做什么!我需要能够直接从键盘上取一个像 0.9 这样的小数,并且能够将它放在一个我可以用来计算的变量中。
I know this is a basic question, but I need some help. Thanks!
我知道这是一个基本问题,但我需要一些帮助。谢谢!
采纳答案by Avindra Goolcharan
double d = new Double(JOptionPane.showInputDialog("Please enter a number between 0 and 1:"));
回答by John Weldon
回答by Tim
Have you tried substituting Doublefor Integer?
您是否尝试过替代Double的Integer?
So Double.parseDouble(JOptionPane.showInputDialog("Please enter a double:"));http://java.sun.com/javase/6/docs/api/java/lang/Double.html#parseDouble(java.lang.String)
所以Double.parseDouble(JOptionPane.showInputDialog("Please enter a double:"));http://java.sun.com/javase/6/docs/api/java/lang/Double.html#parseDouble(java.lang.String)
Or Double.valueOf(JOptionPane.showInputDialog("Please enter a double:"))http://java.sun.com/javase/6/docs/api/java/lang/Double.html#valueOf(java.lang.String)
或者Double.valueOf(JOptionPane.showInputDialog("Please enter a double:"))http://java.sun.com/javase/6/docs/api/java/lang/Double.html#valueOf(java.lang.String)
回答by Pascal Thivent
You should use Double.parseDouble(String). Another option is Double.valueOf(String)and I prefer the later because it's more change tolerant (if the parameter is changed for something else than a String, you may not have to modify your code), even if it creates an unnecessary Doublethat you don't need in your example.
你应该使用Double.parseDouble(String). 另一种选择是Double.valueOf(String),我更喜欢后者,因为它更能容忍变化(如果参数更改为 a 以外的其他内容String,您可能不必修改代码),即使它创建了Double您在示例中不需要的不必要的代码.

