如何在Android中打印带有两位小数的双精度数?
也许这是一个愚蠢的问题,但如果它不创建方法,我无法猜测如何解决它。也许有一种“自然的方式”可以做到这一点,例如 C 语言。问题是:
我有一个 var:
double a;
并且我只想用 2 或 3 位小数来显示它。当我尝试展示它时:
Text.setText("Value of a: " + String.valueOf(a));
它给出了类似的内容:
a的值:5.234966145
我想要的只是
a 的值:5.23
不改变 a 的实际值,因此它显示近似数,但适用于实数。
Maybe this is a silly question, but I cannot guess how to solve it if it's not creating a method. Maybe there's a "natural way" to do it, like in C for example. Here's the problem:
I have a var:
double a;
And I want to show it only with 2 or 3 decimals. When I try to show it:
Text.setText("Value of a: " + String.valueOf(a));
It gives something like:
Value of a: 5.234966145
And i would want just
Value of a: 5.23
Without changing the real value of a so it shows the approximate number but works with the real number.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
要显示最多两位小数的数字,有两种可能性 -
1)首先,您只想显示小数位(如果有)。
例如 - i) 12.10 将显示为 12.1,ii) 12.00 将显示为 12。然后使用
- 2) 其次,您希望显示小数位,而不管小数点的存在 例如 -i) 12.10 将显示为 12.10。 ii) 12 显示为 12.00。然后使用-
For Displaying digit upto two decimal places there are two possibilities -
1) Firstly, you only want to display decimal digits if it's there.
For example - i) 12.10 to be displayed as 12.1, ii) 12.00 to be displayed as 12. Then use-
2) Secondly, you want to display decimal digits irrespective of decimal present For example -i) 12.10 to be displayed as 12.10. ii) 12 to be displayed as 12.00.Then use-
您可以使用 DecimalFormat 或
String.format("%.2f", a);
You can use a DecimalFormat, or
String.format("%.2f", a);
在使用 DecimalFormat 之前,您需要使用以下导入,否则您的代码将无法工作:
格式化的代码是:
Before you use DecimalFormat you need to use the following import or your code will not work:
The code for formatting is:
并且
...在欧洲区域设置中导致“NumberFormatException”错误,因为它将结果设置为逗号而不是小数点 - 将 textView 添加到 editText 中的数字时会发生错误。
这两种解决方案在美国和英国地区都运行良好。
and
...cause "NumberFormatException" error in locale for Europe because it sets result as comma instead of point decimal - error occurs when textView is added to number in editText.
Both solutions are working excellent in locale US and UK.