java中十进制数的乘法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9655878/
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
multiplying decimal numbers in java
提问by FatmaTurk
I have the following code which works when I am multiplying whole numbers however when I try to multiply decimal numbers and display the answer as a decimal number I am getting an error
我有以下代码,当我乘以整数时有效,但是当我尝试乘以十进制数并将答案显示为十进制数时,我收到错误
public void actionPerformed(ActionEvent e) {
int num1=Integer.parseInt(textArea_price.getText());
int num2=Integer.parseInt(textArea_quantity.getText());
int result = num1*num2;
textField_Name.setText(Integer.toString(result));
Any suggestions on what I can change or add to make this code work with decimal numbers is appreciated.
任何关于我可以更改或添加什么以使此代码与十进制数一起工作的建议表示赞赏。
采纳答案by Peter Lawrey
BigDecimal could be what you want.
BigDecimal 可能是您想要的。
textField_Name.setText(
new BigDecimal(textArea_price.getText())
.multiply(new BigDecimal(textArea_quantity.getText())).toString());
回答by Vincent Ramdhanie
If you are expecting real numbers in the text fields then use double rather than int.
如果您希望文本字段中出现实数,则使用 double 而不是 int。
double num1 = Double.parseDouble(textArea_price.getText());
回答by Bohemian
Change int/Integer
to double/Double
.
更改int/Integer
为double/Double
。
Note that double
is imprecise (for example 1.2 * 9
gives 10.799999999
when it should be 10.8
). Consider using BigDecimal
if exactness is required.
请注意,这double
是不精确的(例如1.2 * 9
给出10.799999999
它应该是的时间10.8
)。BigDecimal
如果需要精确性,请考虑使用。
回答by AlexR
Use Double.parseDouble()
instead of Integer.parseInt()
. And use double
type of variables:
使用Double.parseDouble()
代替Integer.parseInt()
。并使用double
变量类型:
double num1 = Double.parseDouble(textArea.getText());
double num1 = Double.parseDouble(textArea.getText());
回答by Hot Licks
My guess is that you're using the term "decimal number" to (erroneously) refer to numbers containing a "decimal point". Such numbers are not integers and cannot be parsed by Integer.toString. They need to be handled as either floating point (float or double) or as BigDecimal.
我的猜测是您使用术语“小数”来(错误地)指代包含“小数点”的数字。这样的数字不是整数,不能被 Integer.toString 解析。它们需要作为浮点数(浮点数或双精度数)或 BigDecimal 处理。
回答by Zelter Ady
float a = Float.parseFloat("121.12");
float b = Float.parseFloat("0.9");
float res = a*b;
String str = Float.toString(res);