使用 double 和 toString 的小数位,android
我正在创建一个简单的程序,它对用户在 EditText 视图中输入的值执行简单的数学函数。前两个 EditText 视图包含整数,最后一个可能是小数,因此答案也可能需要采用小数形式,因此我将 and (vis) 设置为双精度,但如何将小数位限制为四位?一切都运行良好,答案只有许多小数位!
这是我的代码:
public void onClick(View v) {
String a,b,t;
double vis;
EditText txtbox1 = (EditText)findViewById(R.id.A);
EditText txtbox2 = (EditText)findViewById(R.id.B);
EditText txtbox3 = (EditText)findViewById(R.id.t);
TextView tv = (TextView) findViewById(R.id.Answer);
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
t = txtbox3.getText().toString();
vis = ((Integer.parseInt(a)*1) + (Integer.parseInt(b)*2)) / (Double.parseDouble(t));
tv.setText(double.toString(vis));
}
}
非常感谢!
I am creating a simple program that performs simple math functions on the values a user enters in the EditText views. The first two EditText views contain integers and the last could be a decimal, thus the answer could also need to be in decimal form so I set the and (vis) as a double, but how can I limit the decimal places to four? Everything is running fine, the answer is just many decimal places long!
Here is my code:
public void onClick(View v) {
String a,b,t;
double vis;
EditText txtbox1 = (EditText)findViewById(R.id.A);
EditText txtbox2 = (EditText)findViewById(R.id.B);
EditText txtbox3 = (EditText)findViewById(R.id.t);
TextView tv = (TextView) findViewById(R.id.Answer);
a = txtbox1.getText().toString();
b = txtbox2.getText().toString();
t = txtbox3.getText().toString();
vis = ((Integer.parseInt(a)*1) + (Integer.parseInt(b)*2)) / (Double.parseDouble(t));
tv.setText(double.toString(vis));
}
}
Thanks so much!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
String.format()
来确保输出中仅显示 4 位小数。只需将最后一行替换为tv.setText(String.format("%.4f", vis));
。请参阅 http://download.oracle.com/javase/tutorial/java/ data/numberformat.html 了解有关如何使用
String.format()
实现此目的的更多详细信息。You could use
String.format()
to make sure you only get 4 decimal places in your output. Simply replace the last line withtv.setText(String.format("%.4f", vis));
.See http://download.oracle.com/javase/tutorial/java/data/numberformat.html for more details on how to use
String.format()
for this purpose.我认为现在回答有点晚了,但可能对未来有所帮助。
如果我们有一个
double
数字,并且需要获取 4 位十进制值,我们可以将double
乘以 10000,并将double
值转换为一个integer
并再次反转为double
并将该数字除以 10000。I think it's a bit too late to answer, but it may help for future purpose.
If we have a
double
number and we need to get the 4 decimal values we can multiply thedouble
by 10000, and cast thedouble
value into aninteger
and reverse intodouble
again and divide the digit by 10000.如需更多控制,请使用 BigDecimal.round()。您可以使用所需的精度和舍入规则设置
MathContext
(0.5 向上舍入,vs .5 向下舍入等)。For more control, use
BigDecimal.round()
. You can set aMathContext
with the precision and rounding rule you require (.5 is round up, vs .5 is rounded down, etc).